Camel Java DSL - routing on ENUM in header - conent based router or dynamic router

StackOverflow https://stackoverflow.com/questions/6832375

  •  27-10-2019
  •  | 
  •  

Pergunta

I have a bean which produces objects and sends them to a SEDA queue using the ProducerTemplate in Camel.

I send a body and a header:

producerTemp.sendBodyAndHeader(document, "sourceSystem", sourceSys);

Here the header name is sourceSystem and the header object value is an ENUM (sourceSys) which contains the source of the document object containing a number of differnt attribs.

I want to pull messages in a concurrent fashion from the SEDA queue and send them to different endpoints depending on the value of the sourceSys enum.

What is the most efficient EIP in camel to use this and does anyone have an example using Java DSL, I'm not sure how I can test the value of the Enum?

I am thinking I do something like this:

from("seda:a")
    .choice()
        .when(header("foo").isEqualTo(SourceSysEnum.SYSTEM1))
            .to("seda:b")
        .when(header("foo").isEqualTo(SourceSysEnum.SYSTEM2))
            .to("seda:c")
        .otherwise()
            .to("seda:d");

..?

Foi útil?

Solução

You can use the recipient list EIP http://camel.apache.org/recipient-list.html

And then for example use a java bean to compute the uri where the message should go.

from("seda:a")
  .recpientList().method(MyBean.class, "whereToGo");

And in the bean you can use bean parameter binding.

So you can bind the header as follows:

public class MyBean {

   public String whereToGo(String body, @Header("foo") SourceSysEnum sys) {
      ...
   }
}

If you dont need the message body, then you can omit that parameter.

Outras dicas

You could use a Processor combined with a Routing Slip to accomplish this using a switch statement. I'm not sure how much more efficient this will be unless you have a ton of enum values. It will, however, give you more flexibility should you need to add more complicated logic in the future.

from("seda:a")
    .process(new SourceSysRoutingSlipProvider())
    .routingSlip(SourceSysRoutingSlipProvider.HEADER_NAME);


public class SourceSysRoutingSlipProvider : Processor {
  public static String HEADER_NAME="sourceSystemRoutes";

  public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();
    switch( in.getHeader("sourceSystem") ) {
      case SourceSysEnum.SYSTEM1:
         in.setHeader(HEADER_NAME, "seda:b");
         break;
      case SourceSysEnum.SYSTEM2:
         in.setHeader(HEADER_NAME, "seda:c");
         break;
      ...
      default:
         in.setHeader(HEADER_NAME, "seda:d");
         break;
    } 
  }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top