Gert Vanthienen's blog

Monday, October 11, 2010

Traits in the Camel Scala DSL

When using the Java DSL for Camel, you can create a custom RouteBuilder class which defines common elements for all your routes (e.g. standardized error handling). Since you're only able to inherit from a single class, great care must be taken in which common route elements are being added to the parent class.

The Scala DSL allows you to extract those common route elements into traits, which can be mixed into the RouteBuilder in more flexible ways. Consider the scenario where we have two ways we do our error handling: we either want to write a message to the error log or we want to send the message into an error queue.

We can model this by writing two Scala traits, defining the org.apache.camel.scala.dsl.RouteBuilder class as the trait's self type:

trait ErrorQueue { self: RouteBuilder =>
handle[Exception] {
log("Sending ${id} to error queue")
to("seda:errors")
}
}

and

trait ErrorLog { self: RouteBuilder =>

handle[Exception] {
log("Sending ${id} to error log")
to("log:errors")
}

}


Afterwards, we can just add the implementation we want in our own RouteBuilder using a simple with clause.

class MyRouteBuilder extends RouteBuilder
with ErrorLog {

//rest of the route goes here

}


Just replace the with ErrorLog by with ErrorQueue to pick another error handler implementation. And because you can add multiple traits to the same class, this approach allows you to define lots of common route elements and just mix and match those that you need.

Happy Camel riding with the Scala DSL!!

1 Comments:

  • This sound nice.
    Please, what version of camel can this be done? Also, if there is a sample in the repository, kindly point me the direction I can check it out.
    Rgds.

    By Blogger lekkie, At October 12, 2010 at 9:40 AM  

Post a Comment

Subscribe to Post Comments [Atom]



<< Home