An introductory guide to Java Programming for Apache Camel _java

Source: Internet
Author: User
Tags static class apache camel

The Apache camel is a very useful rule engine library that can be used to handle events and information from different sources. You can use different protocols such as VM,HTTP,FTP,JMS or even file systems to deliver messages and keep your operational logic and delivery logic separate, allowing you to focus more on the content of the message.

In this article, I will provide an introductory demo of the Apache Camel Java language (not groovy).

First, create a pom.xml for the 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.0 http:// Maven.apache.org/maven-v4_0_0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Camel-spring-demo</groupid> <artifactId>camel-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> <dependencies> <dependency> <groupid>org.apache.camel</ groupid> <artifactId>camel-core</artifactId> <version>${camel.version}</version> </ dependency> <dependency> <groupId>org.slf4j</groupId> <artifactid>slf4j-simple</ Artifactid> <version>1.7.5</version> </dependency> </dependencies> </project>
 

Here we only use the Camel-core.jar package, which in fact provides a lot of useful components that you might use. For logging purposes, I used slf4j-simple as a logging implementation so that we could see the output from the console.

Next we just need to construct a routing class. Routing is like a directive definition of how a message is passed from one end to another in camel. We will create a Src/main/java/camelcoredemo/timerroutebuilder.java file, send a message to the processor every second, and simply print it out.

Package Camelcoredemo;
 
Import org.slf4j.*;
Import org.apache.camel.*;
Import org.apache.camel.builder.*;
 
public class Timerroutebuilder extends Routebuilder {
static Logger LOG = Loggerfactory.getlogger ( Timerroutebuilder.class);
public void Configure () {from
(' timer://timer1?period=1000 ')
. Process (New Processor () {public
void Process (Exchange msg) {
log.info ("Processing {}", msg);}}
);
}

That's all the need for this example, and now the compilation runs.

bash> mvn compile
bash> mvn exec:java-dexec.mainclass=org.apache.camel.main.main-dexec.args= '-R Camelcoredemo. Timerroutebuilder '

Note that we do not write the main entrance to the Java class, we simply pass the Routebuilder class name as a parameter to Org.apache.camel.main.Main, and then it automatically loads the route.


Control Camelcontext

When Camel is started, it creates a Camelcontext object that has a lot of information about how to run camel, as well as the definition of the route we created. Now if you want to get more control through Camelcontext, you need to write your own main class code. Let me give you a simple example here.

 package Camelcoredemo;
Import org.slf4j.*;
Import org.apache.camel.*;
Import org.apache.camel.impl.*;
 
 
 
 
Import org.apache.camel.builder.*; public class Timermain {static Logger LOG = Loggerfactory.getlogger (timermain.class); public static void Main (string[] Ar GS) throws Exception {new Timermain (). Run ()} void Run () throws Exception {final Camelcontext camelcontext = new Defaul
Tcamelcontext ();
Camelcontext.addroutes (Createroutebuilder ());
Camelcontext.settracing (TRUE);
 
 
 
 
Camelcontext.start (); 
Runtime.getruntime (). Addshutdownhook (New Thread () {public void run () {try {camelcontext.stop ();} catch (Exception e) {
throw new RuntimeException (e);
 
 
 
 
}
}
});
Waitforstop (); Routebuilder Createroutebuilder () {Return to New Timerroutebuilder ();} void Waitforstop () {while (true) {try {Thread.s
Leep (Long.max_value);
catch (Interruptedexception e) {break;}} }
}

As you can see, we have reused the existing Timerroutebuilder class in the Createroutebuilder () method. Our main class now has complete control over when to create, start, and stop Camelcontext. The context (Camelcontext) object allows you to globally control how to configure camel, rather than at the route level. Its Javadoc link gives you all the setter methods, and you can look at what it can do.

Note that we also need to provide a small set of code in our main class. First we need to deal with the graceful shutdown problem, so we added a Java shutdown callback function to invoke the context's stop () method. Second, after the context has been started, we need to add a thread block. If you do not block your main thread after startup, it will simply exit after startup, which is no use. You will keep camel running as a service (like a server) until you press CTRL + C to terminate the process.

To improve the main class of startup Camelcontext

If you don't want to handle the main class setup code as much as the example above, then you can simply inherit the Org.apache.camel.main.Main class provided by Camel-core instead. By taking advantage of this class, you can not only set your context automatically, but also get all the additional command-line features, such as how long the control process will run, enable tracing, load custom route classes, and so on.

Refactoring the next example with the following code:

Package Camelcoredemo;
 
Import org.slf4j.*;
Import org.apache.camel.builder.*;
Import Org.apache.camel.main.Main;
 
public class TimerMain2 extends Main {
static Logger LOG = Loggerfactory.getlogger (timermain2.class);
public static void Main (string[] args) throws Exception {
TimerMain2 main = new TimerMain2 ();
Main.enablehangupsupport ();
Main.addroutebuilder (Createroutebuilder ());
Main.run (args);
}
Static Routebuilder Createroutebuilder () {return
new Timerroutebuilder ();
}
}

Now that the code for the TimerMain2 class is less than before, you can try it, it should be the same as before.

bash> mvn compile
bash> mvn exec:java-dexec.mainclass=camelcoredemo. timermain2-dexec.args= '-t '

Note that after we give the-t option, we will dump route tracking. Use-h to see all available options.

To add a bean using the camel registration mechanism

In the previous Timerroutebuilder example, we have created an anonymous processor in our code. Now if you want to put together several different processor, then using the Camel registration mechanism to add beans will better reduce code clutter. Camel allows you to inject processing as a bean into its registry space, and then you simply call them as bean components. The following is my refactoring code:
 

Package Camelcoredemo;
Import org.slf4j.*;
Import org.apache.camel.*;
Import org.apache.camel.builder.*;
 
Import Org.apache.camel.main.Main; public class Timerbeansmain extends Main {static Logger LOG = Loggerfactory.getlogger (Timerbeansmain.class); c void Main (string[] args) throws Exception {Timerbeansmain main = new Timerbeansmain (); Main.enablehangupsupport (); main
. Bind ("ProcessByBean1", New Bean1 ());
Main.bind ("ProcessAgainByBean2", New Bean2 ());
Main.addroutebuilder (Createroutebuilder ());
Main.run (args); Static Routebuilder Createroutebuilder () {return new Routebuilder () {public void Configure () {from ("Timer://timer1?pe
riod=1000 "). to (" Bean:processbybean1 "). to (" bean:processagainbybean2 ");
}
}; }//Processor beans Static class Bean1 implements Processor {public void process (Exchange msg) {log.info ("I proce
SS {} ", msg); 
} Static class Bean2 implements Processor {public void process (Exchange msg) {log.info ("Second Process {}", msg);}
 }

The route class is now more concise and the processing code has been refactored into separate classes. This approach can help you better organize and test your code when you need to write complex route to implement business logic. It allows you to build reusable pojo beans like Lego blocks. Camel's registry space can also be used for many other purposes, such as the ability to customize many of the endpoint components with additional functionality or to register some information, or to replace the thread pool implementation strategy.

The route example above is made up of a so-called Java DSL, which is more readable and allows you to view all available route methods using the support provided by the IDE.

I hope this article will help you to skip the camel stage.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.