Apache Camel Getting Started Guide for Java Developers

Apache Camel Getting Started Guide for Java Developers

 

Preface

Apache Camel is a very practical rule engine library that can be used to process events and information from different sources. You can use different protocols such as VM, HTTP, FTP, JMS and even file systems to deliver messages, and keep your operation logic and delivery logic separate, which allows you to focus more on the content of the message.

In this article, I will provide an introductory demonstration of Apache Camel in Java language (not Groovy).

First create the 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.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 camel-core.jar package, in fact it provides many useful components you may use. For logging purposes, I used slf4j-simple as the implementation of logging so that we can see the output from the console.

Next we only need to construct a routing class. Routing is like an instruction definition in Camel for how to pass messages from one end to the other. We will create the 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);
}});}}

The above is all that is needed for this example, now compile and run.

bash> mvn compile
bash> mvn exec:java -Dexec.mainClass=org.apache.camel.main.Main -Dexec.args='-r camelcoredemo.TimerRouteBuilder'

Note that here we did not write the main entry of the Java class , we just simply pass the RouteBuilder class name as a parameter to org.apache.camel.main.Main, and then it will automatically load the route.

Control CamelContext

When Camel is started, it will create a CamelContext object, which has a lot of information about how to run Camel, and also contains the definition of the Route we created. Now if you want to get more control through CamelContext, then you need to write your own main class code. Let me give 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[] args) throws Exception {
new TimerMain().run();
}void run() throws Exception {
final CamelContext camelContext = new DefaultCamelContext();
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 new TimerRouteBuilder();
}void waitForStop() {
while (true) {
try {
Thread.sleep(Long.MAX_VALUE);} catch (InterruptedException e) {
break;
}}}}

As you can see, we reuse the existing TimerRouteBuilder class in the createRouteBuilder() method. Now our main class has complete control over when to create, start, and stop CamelContext. The context(camelContext) object allows you to globally control how to configure Camel, not at the Route level. Its JavaDoc link gives all the setter methods, you can study what it can do.

Note that we also need to provide a small amount of setting code in our main class. First of all, we need to deal with the graceful shutdown, so we added a Java shutdown callback function to call the context's stop() method. Secondly, after the context has been started, we need to add a thread blocking. If you don't block your main thread after startup, then it will simply exit after startup, which is useless. You will run Camel as a service (just like a server) until you press CTRL+C to terminate the process.

Improve the main class that starts CamelContext

If you don't want to deal with the main class setting code too much like the above example, then you can simply inherit the org.apache.camel.main.Main class provided by camel-core instead. By using this class, you can not only set your context automatically, but also get all additional command line features, such as controlling how long the process runs, enabling tracking, loading custom route classes, and so on.

Refactored the previous example, the code is as follows:

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 the code of the TimerMain2 class is less than before, you can try it, it should have the same function as before.

bash> mvn compile
bash> mvn exec:java -Dexec.mainClass=camelcoredemo.TimerMain2 -Dexec.args='-t'

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

Add beans with Camel's registration mechanism

In the previous TimerRouteBuilder example, we have created an anonymous Processor in the code. Now if you want to put several different processors together, the way of adding beans using Camel's registration mechanism will better reduce code confusion. Camel allows you to inject processing into its registry space as beans, and then you only need to call them as bean components. The following is my refactored 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);
public static 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 period=1000")
.to("bean:processByBean1")
.to("bean:processAgainByBean2");
}};}// Processor beans
static class Bean1 implements Processor {
public void process(Exchange msg) {
LOG.info("First process {}", msg);
}
}
static class Bean2 implements Processor {
public void process(Exchange msg) {
LOG.info("Second process {}", msg);
}
}
}

Now the Route class is more concise and clear, and the processing code has also been refactored into a separate class. When you need to write a very complex Route to implement business logic, this approach can help you better organize and test your code. It allows you to build reusable POJO beans like "Lego" blocks. Camel's registry space can also be used for many other purposes. For example, you can customize many endpoint components with additional functions or register some information, or replace the thread pool implementation strategy.

The above Route example is constructed using the so-called Java DSL, which is more readable. You can use the support provided by the IDE to view all the methods available for Route.

I hope this article can help you skip the exploration phase of Camel, and remember to follow + forward after reading it

Guess you like

Origin blog.csdn.net/sinat_37903468/article/details/108867958