Archive for August 2009

Groovy and Camel for Monitoring ActiveMQ

I often have the need communicate with backend systems for simple tasks, but do not want to end up going to all of the trouble of creating an application.  For database, I used to just use Perl and DBI for simple tasks, but even setting up DBI can be some work depending on your database server.  What I really like is being able to quickly write a script in a single file and run it with no setup necessary — that is what makes Groovy and Camel with Grape such a great combination.

Let’s look at a simple script for monitoring ActiveMQ advisory messages:

   1: import org.apache.camel.*;

   2: import org.apache.camel.impl.*

   3: import org.apache.camel.language.groovy.*

   4: import org.apache.camel.component.activemq.*

   5: import org.apache.activemq.camel.component.*

   6: import org.apache.log4j.*

   7:  

   8: @Grab(group='org.apache.camel', module='camel-groovy', version='2.0-M2')

   9: @Grab(group='org.apache.camel', module='camel-jms', version='2.0-M2')

  10: @Grab(group='org.apache.camel', module='camel-core', version='2.0-M2')

  11: @Grab(group='org.apache.activemq', module='activemq-all', version='5.2.0')

  12: @Grab(group='org.apache.activemq', module='activemq-camel', version='5.2.0')

  13: class Routes extends GroovyRouteBuilder {

  14:   public void configure(){

  15:         def log = { exchange -> if (exchange) println exchange } as Processor;

  16:  

  17:         from("activemq:queue:ActiveMQ.Advisory.>").

  18:           process(log);

  19:     }

  20: }

  21:  

  22: def camelCtx = new DefaultCamelContext()

  23: camelCtx.addComponent("activemq", ActiveMQComponent.activeMQComponent("tcp://127.0.0.1:61616"))

  24: camelCtx.addRoutes(new Routes())

  25: camelCtx.start()

 

All you have to do is save this to a file and run “groovy Script.groovy” – no uploading JAR files or classpath setup required thanks to Grape.  You can see in the script how simple it is to define a Camel processor using Groovy coercion.  With a few modifications, I also use this script as a base for draining dead letter queues, moving message from one queue to another, etc.

Of course, just printing out advisory messages is not all that useful.  Say you want to get notified by email when there is a slow consumer.  Just add dependencies for the necessary mail JARs and and change your route:

   1: from("activemq:queue:ActiveMQ.Advisory.SlowConsumer.*").

   2:   mail("smtp://monitor-list@mycompany.mailserver")

With all of the different Camel components, there are a lot of things you can do with the information – send an IM, log to a database, or write to a file.