Thursday, January 29, 2009

POJOs can route too!

In Camel we have several really cool Domain Specific Languages (DSLs) for easily expressing routing rules. But you don't need to learn these to use Camel. Starting with a POJO, you can use annotations to produce, consume or route messages to any Camel endpoint.

Take the following bean for example

public class BeanThatTalksCamel {
@Produce(uri="activemq:myQueue")
ProducerTemplate producer;

@Consume(uri = "file:a/path")
public void onFileSendToQueue(String body) {
producer.sendBody(body);
}
}


We use the @Consume annotation to mark onFileSendToQueue as a consumer of any messages coming from the file:a/path endpoint. To enable the bean to send messages to the activemq:myQueue endpoint, we use the @Produce annotation. All conversions between Files, Strings and JMS Messages are automatic. Pretty easy huh?

We also have the @RecipientList annotation that turns any bean into a dynamic Recipient List.


public class RecipientListBean {
@Consume(uri = "activemq:myQueue")
@RecipientList
public List route(String body) {
// return list of recipients based on message body
}
}


Here we consume JMS messages from myQueue and based on the body, send it out to a list of recipients. Again, very easy. If you're a ServiceMix user, Gert mentions how to use this trick from a ServiceMix perspective too, go check it out!

If you need more info, I've put all of these concepts into a little demo here. As always, if you need help using Camel, please get in touch.

No comments: