Hello!
This is the second text about Apache Camel, there will be a lot more in the future. Purpose of this articles is to present people the real power of Camel, maybe some of you will find a use case where you can use this framework instead of writing boilerplate code over and over.
Today we will use Camel to call API endpoint and handle some of the exceptions.
Dependencies
Routes
Scheduler route
If you remember from introduction, this is a scheduler route, it will trigger a message every 120 seconds and send it to "direct:httpRoute" route. I am using synchronous "direct" component, there is also asynchronous "seda" component.
@Override"
public void configure() {
from("timer:scheduler?period=120000")
.log("Scheduled job!")
.to("direct:httpRoute");
}
Http route
This is a HTTP client route, it will call the bittrex rest API and get crypto currencies and log the response.
@Override
public void configure() {
from("direct:httpRoute")
.log("Http Route started")
.setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.GET)
.to("https://api.bittrex.com/api/v1.1/public/getcurrencies")
.log("Response : ${body}");
}
Error Handlers
If you want to cover some exceptions there is a two options.
- Default error handler
- onException clause to handle specific class exceptions.
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:errorHandler"));
onException(HttpOperationFailedException.class)
.log("${exception}")
.to("mock:errorHandler");
from("direct:httpRoute")
.log("Http Route started")
.setHeader(Exchange.HTTP_METHOD).constant(HttpMethod.GET)
.to("https://api.bittrex.com/api/v1.1/public/getcurrencies")
.log("Response : ${body}");
}
Results
This is all for this tutorial, if something is not clear, feel free to contact me I will gladly answer any question.
Thanks!
Top comments (4)
Hi Djordje,
i am a beginner with Camel. Can you give me a tip how to parse the Rest Response. For Example instead of the .log("Response : ${body}") in the above Code, i would like to parse the Response, convert the Json structure and reply back to the caller.
Hey sorry for the late response i missed the notification :S
Check this video i created to see how to deserialize and serialize JSON.
youtube.com/watch?v=KE_IAHkFdmE
Hope this helps you.
George
Hey @djordje,
I am too new to camel, if you have any github repo for this tutorial, pls do share me link. It will be great. Thanks
Hello Karshll,
Here is a github repo as you requested :)
github.com/djoleB/apache_camel_tut...
Stay safe,
George