Tuesday, November 19, 2013

Discovering the power of Apache Camel

These last years, ESB software has been getting more and more popular. If most people usually know what is an ESB, they are fewer to clearly understand the exact role of the different components of such architecture.
For instance, Apache ServiceMix is composed of three major components : Apache Karaf (the OSGI container), Apache ActiveMQ (the message broker) and Apache Camel. By the way, what is exactly Camel ? What is a « routing and mediation engine » ? What is it useful for ?




I’ve been working with Camel for about one year now, and I think – although not being at all a Camel guru, that I now have enough hindsight to make you discovering the interest and power of Camel, using some very concrete examples.For the sake of clarity, I will, for the rest of this article, be using the Spring DSL – assuming the reader is familiar with Spring syntax.

The Use Case

Let us imagine we want to implement the following scenario using Camel. Requests for product information are coming as flat files (in CSV format) in a specific folder. Each line of such file contains a single request of a particular customer about a particular car model. We want to send these customers an email about the car they are interested in. To do so, we first need to invoke a web service to get additional customer data (e.g. their email). Then we have to fetch the car characteristics (lets us say a text) from a database. As we want a decent look (ie HTML) for our mails, a small text transformation will also be required.
Of course, we do not want a mere sequential handling of the requests, but would like to introduce some parallelism. Similarly, we do not want to send many times the exact same mail to different customers (but rather a same unique mail to multiple recipients). It would be also nice to exploit the clustering facilities of our back-end to load-balance our calls to web services. And finally, in the event the processing of a request failed, we want to keep trace, in some way or another, of the originating request, so that we can for instance send it by postal mail.

A (possible) Camel implementation :


    

        
        
            
        

        
        
            
            
                
            
            
                ${body}
                
                    ${body[1]}
                
                
                    ${body[2]}
                
                
                    ${body[0]}
                
                
            
        

        
        
            
            
                
                
            
        

        
        
            
            
                
            
            
                
                
                
            
            
                /customer/general/email
            
        

        
        
            
            
                
                    header.carModelId
                
                
                    60000
                
                
                    ${body}
                
                
                    
                    
                
            
        

        
        
            
            
                header.carModelId
            
            
                
                
            
        

        
        
            
            
            
        

    



    
    
        
    

    
    
        
        
        
        
    

    
    

And the code of the (only!) Java class :
public class ConcatBody implements AggregationStrategy {

 public static final String SEPARATOR = ", ";

 public Exchange aggregate(Exchange aggregate, Exchange newExchange) {
        if (aggregate == null) {
         // The aggregation for the very exchange item is the exchange itself
         return newExchange;
        } else {
         // Otherwise, we augment the body of current aggregate with new incoming exchange
             String originalBody = aggregate.getIn().getBody(String.class);
             String bodyToAdd = newExchange.getIn().getBody(String.class);
             aggregate.getIn().setBody(originalBody + SEPARATOR + bodyToAdd);
             return aggregate;
        } 
    }

}

Some explanations

  • The “route1” deals with the processing of incoming flat files. Thee file content is first unmarshalled (using CSV format) and then split into lines/records. Each line will be turned into an individual notification that is sent to a JMS queue.
  • The “route2” is consuming these notifications. Basically, fulfilling a request means doing two things in sequence (“pipeline”) : get the customer email (route3) and send him a mail (route4). Note the ‘maxConcurrentConsumers’ parameter that is used to easily answer our parallelism requirement.
  • The “route3” models how to get the customer email : simply by parsing (using XPath) the XML response of a (secured) REST web service that is available on two back-end nodes.
  • The “route4” contains the logic to send massive mails. Each time 10 similar send requests (that is, in our case, 10 requests on same car model) are collected (and we are not ready to wait more than 1 minute) we want the whole process to be continued with a new message (or « exchange » in Camel terminology) being the concatenation of the 10 assembled messages. Continuing the process means: first prepare the mail body (route5), and then send it to the group (route6).
  • In “route5“, a SQL query is issued in order to get the appropriate text depending on the car model. On that result, we apply a small XSL-T transformation (that will replace the current exchange body with the output of the xsl transformation).
  • When entering “route6“, an exchange contains everything we need. We have the list of recipients (as header), and we also have (in the body) the html text to be sent. Therefore we can now proceed to the real sending using SMTP protocol.
  • In case of errors (for instance, temporary network problems) – anywhere in the whole process, Camel will make maximum two additional attempts before giving up. In this latter case, the originating message will be automatically placed by Camel into a JMS Dead-Letter-Queue.

Conclusion

Camel is really a great framework – not perfect but yet great. You will be surprised to see how few lines of code are needed to model a complex scenario or route. You could also be glad to see how limpid is your code, how quickly your colleagues can understand the logic of your routes.
But it’s certainly not the main advantage. Using Camel primarily invites you to think in terms of Enterprise Integration Patterns (aka “EIP”); it helps you to decompose the original complexity into less complex (possibly concurrent) sub-routes using well-known and proven techniques, thereby leading to more modular, more flexible implementations. In particular, using decoupling techniques facilitates the potential replacement or refactoring of individual parts or components of your solution.
 
Reference: Discovering the power of Apache Camel from our W4G partner Bernard Ligny.

No comments: