Apache camel tutorial LEARNOVITA

Apache Camel Tutorial – EIP, Routes, Components | Ultimate Guide to Learn [BEST & NEW]

Last updated on 10th Aug 2022, Blog, Tutorials

About author

Vidhyawati (Sr Java Developer )

Vidhyawati is a Java developer with 8+ years of experience in a flexible business process management suite that is written in Java. She has skills in JavaScript, HTML, CSS, SQL, Python, BPMN, Red Hat process, Drools software, Jira, and Appian.

(5.0) | 18352 Ratings 2109

Introduction to camel :

Apache camel is Associate in open supply framework that gives rule-based routing and mediation engine. Camel provides Associate in open source implementation of varied EIPs. It makes integration easier by providing property to awfully massive form of transports and Apis. for instance, you’ll simply route JMS to JSON, JSON to JMS, protocol to JMS, FTP to JMS, even protocol to protocol, and property to Microservices

Terminology and design

Let’s currently discuss the essential camel language and design.

First, we’ll have a glance at the core camel ideas here:

  • Message contains knowledge that is being transferred to a route. Every message features a distinctive symbol and it’s made out of a body, headers, and attachments.
  • Exchange is that the instrumentation of a message and it’s created once a message is received by a shopper throughout the routing method. Exchange permits differing kinds of interaction between systems – it will outline a unidirectional message or a request-response message.
  • Endpoint could be a channel through that system will receive or send a message. It will visit an online service URI, queue URI, file, email address, etc.
  • Component acts as Associate in Nursing termination manufactory. to place it merely, parts supply Associate in Nursing interface to totally different technologies victimization identical approach and syntax camel already supports loads of parts in its DSLs for nearly each potential technology, however it conjointly offers the power for writing custom parts.
  • Processor could be a straightforward Java interface that is employed to feature custom integration logic to a route. It contains one method technique wont to preform custom business logic on a message received by a shopper.At a high level, the design of camel is straightforward. camel Context represents the Camel runtime system and it wires totally different ideas like routes, parts or endpoints.

Features of camel:

  • Camel supports pluggable knowledge formats and sort converters for such message transformations, thus new formats and converters will be additional in future. Currently, it supports many in style formats and converters; to call many – CSV, EDI, JAXB, JSON, XmlBeans, XStream, Flatpack, Zip.
  • Camel supports pluggable languages to write down predicates in line. a number of the supported languages embody JavaScript, Groovy, Python, PHP, Ruby, SQL, XPath, XQuery.
  • Camel supports the POJO model so you’ll be able to enter Javabeans at numerous points.
  • Camel eases testing of such giant distributed and asynchronous systems by exploitation electronic messaging.

When to Use Apache Camel?

Apache is impressive if you wish to integrate many applications with completely different protocols and technologies. Why? there’s one feature (besides supporting numerous technologies and besides supporting completely different programming languages) that actually appreciate a lot each integration uses an equivalent concepts despite that protocol you employ.Despite that technology you employ. Despite that domain specific language (DSL) you employ – it may be Java, Scala, Groovy or Spring XML. you are doing it an equivalent manner. Always there’s a producer, there’s a shopper, there square measure endpoints, there square measure EIPs, there square measure custom processors and there square measure parameters.

Apache Camel benefits

  • Best light-weight integration answer.
  • Producing to and overwhelming from any electronic messaging system.
  • Message sort conversion.
  • Large support library.
  • Camel integrates well with standard frameworks like Spring Boot, and alternative middleware merchandise, permitting it to be deployed but you wish to deploy it.
  • There are over one hundred fifty elements for the artiodactyl framework that facilitate integrate with various computer code platforms.

Architecture:

The diagram’s focal point is CamelContext, the brains of Apache Camel. The “Camel” in this case is the CamelContext, the runtime Camel that holds everything together.When defining a route, one of Camel’s DSLs is used. Each EIP has a corresponding name in the DSLs, and processors are used to perform the necessary transformations and manipulations on messages as they are routed. Camel’s components serve as nodes from which external systems can be connected. Components supply an endpoint interface for these systems to communicate with the rest of Camel.

Steps to use Apache Camel:

Dependencies in Maven:

Adding the necessary Maven dependency is the first step toward using Camel.

  • org.apache.camel
  • camel-core
  • 2.18.0
  • Copy

Specialist Jargon:

Camel’s core functionality is its routing engine and associated routes. The rationale and flow of combining multiple systems is contained in routes.Camel provides a number of DSLs, or domain-specific languages, for use with popular programming languages like Java and Groovy, making route definition simpler and cleaner. However, it also supports Spring DSL route definitions in XML.Most of the capabilities are accessible in both Java DSL and Spring DSL, thus choosing between the two is largely a matter of personal opinion.

Terminology

The information in the message is being sent along a specific path. With its own distinct identification, each message is built from a body, headers, and any relevant attachments.When a message is routed and delivered to a consumer, an exchange is generated to hold the message. Communication through exchange can take several forms; for example, it can describe a one-way message or a request-response exchange between two systems.Each endpoint is a communication path that a system can use to either receive or transmit data. It may be the address of a web service, a queue, a file, an email address, etc.As an endpoint factory, the component plays a crucial role. Components, in their simplest form, provide a uniform interface for communicating with many technologies. Camel provides a large number of components through its DSLs for practically every technology imaginable and also allows for the creation of one’s own components.Processor is a straightforward Java interface for including individualised logic in route integration. It has just one process method for executing user-defined business logic on incoming messages.At a high level, the architecture of Camel is simple. CamelContext represents the Camel runtime system and it wires different concepts such as routes, components or endpoints.And below that, processors handle routing and transformations between endpoints, while endpoints integrate different systems.

Using Spring DSL for Routing:

In order to define a route with Spring DSL, we utilise an XML file to specify our routes and processors. Since Spring doesn’t require any coding for route configuration, we can take advantage of total inversion of control.

  • <"bean id="fileRouter" class="com.baeldung.camel.file.FileRouter" />
  • <"bean id="fileProcessor" class="com.baeldung.camel.file.FileProcessor" />
  • <"camelContext xmlns="http://camel.apache.org/schema/spring">
  • <"routeBuilder ref="fileRouter" />

This way we tell Camel to use FileRouter class which holds the definition of our route in Java DSL:

  • public class FileRouter extends RouteBuilder
  • { private static final String SOURCE_FOLDER =
  • “src/test/source-folder”;
  • private static final String DESTINATION_FOLDER =
  • “src/test/destination-folder”;
  • @Override
  • public void configure() throws Exception {
  • from(“file://” + SOURCE_FOLDER + “?delete=true”).process
  • ( new FileProcessor()).to(“file://” + DESTINATION_FOLDER);
  • }
  • }

To verify this, we need to load our Spring CamelContext by creating an instance of

  • ClassPathXmlApplicationContext:
  • @Test
  • public void moveFolderContentSpringDSLTest() throws InterruptedException { ClassPathXmlApplicationContext
  • applicationContext = new ClassPathXmlApplicationContext(“camel-context.xml”);
  • Thread.sleep(DURATION_MILIS);
  • applicationContext.close();
  • }

EIP Feature in Apache Camel:

Apache Camel is a robust integration platform that is available as open source software. It is built on Enterprise Integration Patterns (EIP), and it features strong Bean Integration. You can construct EIP routing with Camel by using Camels intuitive Domain Specific Language (DSL), which is based on Java (also known as fluent builder), or XML. Because Camel uses URIs for endpoint resolution, it is relatively simple to deal with any sort of transport, including HTTP, REST, JMS, web services, File, FTP, TCP, Mail, JBI, Bean (POJO), and many more. Camel also supports a wide variety of programming languages. Camel also offers support for a variety of widely used data formats, including CSV, EDI, FIX, HL7, JAXB, Json, and Xstream, among others. Camel is an application programming interface (API) for integration that may be incorporated into any server of your choosing, such as J2EE Server, ActiveMQ, Tomcat, OSGi, or it can operate independently. You are able to totally isolate the logic of your company from the logic of the integration thanks to the loose coupling that can be defined with Camels Bean Integration. Because Camel is based on a modular architecture, it enables you to plug in your own component or data type, making it possible for these additions to blend in smoothly with modules that are already there. Camel offers a test kit with powerful mock and assertion features, making it suitable for both unit testing and integration testing.

EIP- Splitter

Using the EIP patterns’ Splitter, users can separate a message into its constituent parts for further processing.

  • package com.javainuse;
  • import org.apache.camel.builder.RouteBuilder;
  • public class SimpleRouteBuilder extends RouteBuilder {
  • @Override
  • public void configure() throws Exception {
  • from(“file:C:/inputFolder”).split().tokenize(“\n”).to(“jms:queue:javainuse”);
  • }
  • }

EIP- Content Based Router:

When a message arrives, the Content-Based Router analyses its contents and sends it to the appropriate destination channel. When a Content-Based Router is used, the message producer only needs to deliver messages to a single channel; from there, the router will determine which destination the messages should be sent to. This removes the burden from the sending application and removes the need to tightly bind the message producer to individual receiver channels.

  • package com.javainuse;
  • import org.apache.camel.builder.RouteBuilder;
  • public class SimpleRouteBuilder extends RouteBuilder {
  • @Override
  • public void configure() throws Exception {
  • from(“file:C:/inputFolder”).split().tokenize(“\n”).to(“direct:test”);
  • from(“direct:test”).
  • choice().
  • when(body().contains(“javainuse1”))
  • .to(“jms:queue:javainuse1”).
  • when(body().contains(“javainuse2”))
  • .to(“jms:queue:javainuse2”)
  • .when(body().contains(“javainuse3”))
  • .to(“jms:queue:javainuse3”).
  • otherwise().
  • to(“jms:queue:otherwise”);
  • }
  • }
  • }

EIP- Message Filter:

A Content-Based Router, of which the Message Filter is a subtype, is a device that processes and routes messages. If the message meets a given set of conditions, it is forwarded to a different channel. Unless the condition is met, the message is ignored.

  • package com.javainuse;
  • import org.apache.camel.builder.RouteBuilder;
  • public class SimpleRouteBuilder extends RouteBuilder {
  • @Override
  • public void configure() throws Exception {
  • from(“file:C:/inputFolder”).split().tokenize(“\n”).to(“direct:test”);
  • from(“direct:test”).
  • filter(body().contains(“javainuse1”))
  • .to(“jms:queue:javainuse1”);
  • }
  • }

Recipient List

With the help of a Content-Based Router, we can send a message to the right system depending on its specific contents. When a message is sent to a channel, the router will automatically pick it up and forward it to the appropriate destination without any intervention from the original sender.

  • package com.javainuse;
  • import org.apache.camel.Exchange;
  • import org.apache.camel.Processor;
  • import org.apache.camel.builder.RouteBuilder;
  • public class SimpleRouteBuilder extends RouteBuilder {
  • @Override
  • public void configure() throws Exception {
  • from(“file:C:/inputFolder”).split().tokenize(“\n”).to(“direct:test”);
  • from(“direct:test”)
  • .process(new Processor() {
  • public void process(Exchange exchange) throws Exception {
  • String recipient = exchange.getIn().getBody().toString();
  • String recipientQueue=”jms:queue:”+recipient;
  • exchange.getIn().setHeader(“queue”, recipientQueue);
  • }
  • }).recipientList(header(“queue”));
  • }
  • }

Wire Tap:

With Wire Tap, you can divert communications even as they’re en route to their final destination.

  • package com.javainuse;
  • import org.apache.camel.Exchange;
  • import org.apache.camel.Processor;
  • import org.apache.camel.builder.RouteBuilder;
  • public class SimpleRouteBuilder extends RouteBuilder {
  • @Override
  • public void configure() throws Exception {
  • from(“file:C:/inputFolder”).split().tokenize(“\n”).to(“direct:test1”);
  • from(“direct:test1”)
  • .wireTap(“jms:queue:DeadLetterQueue”)
  • .to(“direct:test2”);
  • from(“direct:test2”)
  • .process(new Processor() {
  • public void process(Exchange arg0) throws Exception {
  • //Some logic here
  • }
  • });
  • }
  • }

Conclusion

Apache camel is associate awful framework to integrate applications with totally different technologies. the most effective factor is that you just perpetually use identical ideas. Besides, support several|for several} many technologies, sensible error handling and simple automatic testing create it prepared for integration comes. Because the quantity of applications and technologies in every company can increase additional, Apache camel contains a nice future. these days we’ve got application silos, in 10 years square measure going to} most likely have cloud silos that are deployed in look App Engine, CloudFoundry, Amazon EC3, or the other cloud service. therefore I hope that Apache camel won’t oversleep to be prepared for the cloud era, too (e.g. by giving parts to attach to cloud frameworks easily). however that’s future. At the instant you actually ought to do this framework out, if you have got to integrate applications within the JVM / Java surroundings.

Are you looking training with Right Jobs?

Contact Us

Popular Courses