Apache Camel – Polling Rest Service

Maven Dependencies

<dependency>
	<groupId>org.apache.camel</groupId>
	<artifactId>camel-core</artifactId>
	<version>${camel-version}</version>
</dependency>

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-http</artifactId>
    <version>${camel-http-version}</version>
</dependency>

Service Class

package com.dineshkrish;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class MyRestService {

	public void doSomething(String response) {
		
		System.out.println(response);
	}
}

Example Program

package com.dineshkrish;

import org.apache.camel.CamelContext;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;

/**
 * 
 * @author Dinesh Krishnan
 *
 */

public class PollRest {

	public static void main(String[] args) throws Exception {

		// creating the camel context
		CamelContext context = new DefaultCamelContext();

		try {

			// adding the routes to the camel
			context.addRoutes(new RouteBuilder() {

				@Override
				public void configure() throws Exception {

					// creating an instance for my bean
					MyRestService service = new MyRestService();
					
					from("timer://poll?fixedRate=true&delay=0&period=5000") // start immediately and poll every 5 second
					.to("https://jsonplaceholder.typicode.com/users/1") 
					.bean(service, "doSomething");
				}
			});

			while (true) {
				// start the context
				context.start();
			}

		} catch (Exception e) {
			// stop the context
			context.stop();
			System.out.println(e.getMessage());
		}

	}
}

Output

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
{
  "id": 1,
  "name": "Leanne Graham",
  "username": "Bret",
  "email": "[email protected]",
  "address": {
    "street": "Kulas Light",
    "suite": "Apt. 556",
    "city": "Gwenborough",
    "zipcode": "92998-3874",
    "geo": {
      "lat": "-37.3159",
      "lng": "81.1496"
    }
  },
  "phone": "1-770-736-8031 x56442",
  "website": "hildegard.org",
  "company": {
    "name": "Romaguera-Crona",
    "catchPhrase": "Multi-layered client-server neural-net",
    "bs": "harness real-time e-markets"
  }
}

Hello, folks, I am a founder of dineshkrish.com. I love Java and Open source technologies, If you find my tutorials are useful, please consider making donations to these charities.