Amarendra Reddy Amarendra Reddy - 29 days ago 8
Java Question

Use a method as producer in camel route

I have method which every now and then generates a string. I would like to register method as uri and produce a exchange method which will be used as input for a route.

The method is call by a different class

SampleClass sc = new SampleClass();
sc.sampleMethod("Hello");


Eg:

public class SampleClass{
@Produce(uri = "direct:consumerMethod")
ProducerTemplate producer;
public sampleMethod(Object obj){
producer.sendBody(object);
}
}


The route is defined as below:

@Override
public void configure() {
from("direct:consumerMethod").process(new GenerateD());
}


But the route doesnt call GenerateD class when i produce using the sampleMethod. Is this not feasible or am i doing something wrong?

Answer Source

Finally this is what worked for my use case.

Starting camelcontext as below:

CamelContext camelContext = new DefaultCamelContext();
camelContext.addRoutes(new SampleRoute());
camelContext.start();

My routebuilder class :

    class SampleRoute extends RouteBuilder {

    @Override
    public void configure() {
        try
        {
            from("direct:consumerMethod").process(new DDT());
        }catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

I then create a interface which has a sendMessage method.

public interface DDTConsumer {

    public String sendMessage(Object object);

}

Now i implement this method to create an endpoint of this interface and send a message to the endpoint.

DDTConsumer ddt;
try {
    ddt = new ProxyBuilder(camelContext).endpoint("direct:consumerMethod").build(DDTConsumer.class);
    ddt.sendMessage(msg.getValue());
    } catch (Exception e) {
        e.printStackTrace();
    }

This solved my problem and the route is working fine now. Hope it helps others as well.