Apache Camel is a very practical rule engine library that can be used to process events and information from different sources. You can transmit messages in different protocols such as VM, HTTP, FTP, JMS, and even in the file system, and keep your operating logic and transmission logic separation, which can make you more focused on the content of the message.
In this article, I will provide a Java language Apache Camel entry demonstration.
First create a pom.xml of a Maven project.
<? xml version = "1.0" encoding = "UTF-8"?> <Project xmlns = "http://maven.apache.org/pom/4.0.0" xmlns: xsi = "http://www.w3 .org/2001/xmlschema-instance "XSI: Schemalocation =" http://maven.apache.org/pom/4.0.0http://maven.APache.org/maven- v4_0.xsd "> <MODELVERSISIINISIINISIINISINISIINISINISINISION"> 4.0. 0 </Modelversion> Camel-Spring-Demo </group> <Artifactid> Came L-SPRING-Demo </ArtiFactid> <Version> 1.0-Snapshot </Version> <Packaging> jar </packaging> <properTies> <Project.build.SourceEncoding> UTF-8 </project.build.sourceEncoding> <Camel.Version> 2.11.1 </Camel.version> </Properties> Ency> <Groupid> ORG.APACHE.CAMEL </Groupid> <ArtiFactid> Camel-Core </Artifactid> <Version> $ {Camel.Version} </version> </dependency> <Dependency> ORG.SLF4J </groupid> <Arttifactid> SLF4J-SIMPLE </Artifactid> <Version> 1.7.5 </version> </dependency> </dependencies> </Project>Here we only use the Camel-Core.jar package, in fact it provides many practical components you may use. For the purpose of log records, I used SLF4J-SIMPLE as the implementation of the log record, so we can see the output from the console.
Next we only need to construct a routing class. Routes are defined by how to pass the message from one end to the other end. We will create SRC/Main/Java/Camelcoredemo/Timerroutebuilder.java files, send a message to the processor every second, and print it simply.
Package Camelcoremo; Import org.slf4j.*; Import org.apache. Camel.*; Import org.apache.builder.*; Tends Routebuilder {Static Logger Log = LoggerFactory.GetLogger (Timerroutebuilder.class); PUBLIC void configure () {from ("time: // timer1? Period = 1000") .process (New Processor () {PUBLIC VOID PROCESS (Exchange MSG) {log.info ("Processing {}", msg);}} );}}The above is all the need for this example, and now compile and run.
Bash> MVN CompileBash> MVN Exec: Java -Dexec.MainClass = ORG.APACHE.CAMEL.MAIN.Main -Dexec.args = ' -R CamelCoremoRoutebuilder'
Note that here we did not write the Main entrance of the Java class. We just simply passed the Routebuilder class name to Org.apache. Camel.main.min, and then it will automatically load the routing.
Control CamelContext
When the Camel is started, it will create a CamelContext object, which has a lot of information about how to run Camel, and also includes the definition of Route we created. Now if you want to get more control through CamelContext, then you need to write your main code. I am here a simple example.
Package Camelcoremo; Import org.slf4j.*; Import org.apache.camel.*; Import org.apache. Camel.impl.*; Import ; PUBLIC Class Timermain {Static Logger Log = LoggerFactory .getLogger (Timermain.class); Public Static Void Main (String [] ARGS) Throws Exception {New Timermain (). Run ();} Void Run () Throws Exception CamelContext CamelContext = New DefaultCamelContext (); CamelContext.addroutes (Creatroutebuilder ()); CamelContext.Settracing (True); CamelContext.start (); Runtime.getruntime (). AddshutdownHook (new thread () {public d run () {trylContext.stop ();} Catch (Exception e) {Throw New Runtimeexception (E);}}); WaitForsstop ();} Routebuilder Createroutebuilder () {Return New Timerroutebuilder (); {While (TRUE) {try {thread.sleep (long. Max_value);} Catch (interruptedException E) {break;}}}}It can be seen that we have reused the existing Timerroutebuilder class in the Creteroutebuilder () method. Now our main class has fully controlled when when it is created, started, and stopped CamelContext. Context (CamelContext) object allows you to control how to configure Camel in a global, not at the Route level. Its Javadoc link gives all the setter methods, and you can study what it can do.
Note that we also need to provide a small amount of code in our main category. First of all, we need to deal with the problem of elegant closure, so we added a Java closing function to call the stop () method of the Context. Secondly, after Context has started, we need to add a thread block. If you do not block your main thread after startup, then it will simply exit after starting, and it will be useless. You will run Camel as a service (like a server) until you press the Ctrl+C key to terminate the process.
Improve the main class that starts to launch CamelContext
If you don't want to process the main class settings code as much as the above example, then you can simply inherit the ORG.APACHE. CAMEL.Main.main class provided by Camel-Core as instead. By using this class, you can not only allow your Context to automatically set, but also obtain all additional command line characteristics, such as how long the control process runs, enables tracking, loads a custom Route class, and so on.
Reconstruct the following example, the code is as follows:
Package caredemo; Import org.slf4j.*; Import org.apache.camel.builder.*; Import org.apache.main.main; Public Class Timermain2 ds main {static logger log = loggerFactory.getLogger (timermain2.class) ; PUBLIC Static Void Main (String [] ARGS) Throws Exception {Timermain2 main = New Timermain2 (); Main.enablehangUpsUpport (); UTebuilder ()); main.run (args);} Static Routebuilder Creteroutebuilder () {Return New Timerroutebuilder ();}} Now the code of Timermain2 is less than before, you can try it, it should be the same as the previous features.
Bash> MVN Compilebash> MVN Exec: Java -Dexec.MAINCLASS = CamelCoremo.Timermain2 -Dexec.args = ' -T'
Note that after we give the -t option, Route tracking will be reserved. Use -H will see all available options.
Add bean with Camel's registration mechanism
In the previous Timerroutebuilder example, we have created an anonymous processeor in the code. Now if you want to put a few different procesors together, adding a bean to adding a Camel registration mechanism will better reduce the code confusion. Camel allows you to use processing as Bean into its registry space, and then you only need to call them as bean components. The following is my reconstruction code:
Package caredemo; Import org.slf4j.*; Import org.apache.camel.*; Import org.apache.builder.*; Import ; PUBLIC CLASS TIMEBEANSMAIN EXTENDS Main {Static Logger Log = LoggerFactory.getLogger (TimerBeansmain.class); Public Static Void Main (String [] Args) Throws Exception {Timerbeansmain Main = New TimerBeansmain (); main.enablehangupsupport (); main.bind ("procesSSSBYBEAN1", New Bean1 ()) ; main.bind ("procesagainbybybean2", new bean2 ()); main.addroutebuilder (createroutebuilder ()); main.run (args);} Static Routebuilder lder () {Return New Routebuilder () {Public void configure () { From ("" timer: // timer1? Period = 1000 ") .to (" Bean: ProcessBybean1 ") .to (" Bean: ProcessAgainBybean2 "); ENTS Processor {Public Void Process ( Exchange msg) {Log.info ("First Process {}", msg);}} Static Class Bean2 Implements Processor {Public Void Process (Exchange MSG) {Log.info ("SEC OND Process {} ", msg);}} }Now the Route class is more concise and clear, and at the same time, the processing code has also been reconstructed into an independent class. When you need to write a very complicated Route to achieve business logic, this method can help you better organize and test your code. It allows you to build POJO Bean that can be reused like "Lego". Camel's Registry Space can also be used for many other uses. For example, you can customize many information or register some information with additional functions, or replace things within the thread pool implementation strategy.
The above Route example is composed of so -called Java DSL. Its readability is high. You can use the support provided by IDE to view all methods that can be used for route.
I hope this article can help you skip the Camel's exploration stage.