Posted In: Spring, Spring REST

Spring Asynch Rest Client – Using Netty library example1

Usecase

Application needs to use Netty library to call REST services. Spring provides Netty factory to do that. By default Spring will use default JDK capabilities to call REST services.

Maven entry for netty

<dependency>
    <groupId>io.netty</groupId>
    <artifactId>netty-all</artifactId>
    <version>4.1.13.Final</version>
</dependency>

 

package com.example;

import java.net.URI;

import org.apache.commons.io.IOUtils;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.AsyncClientHttpRequest;
import org.springframework.http.client.AsyncClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.Netty4ClientHttpRequestFactory;
import org.springframework.util.concurrent.ListenableFuture;

public class AsyncRestTmpltNetty {
	public static void main(String[] args) {
		new AsyncRestTmpltNetty().proceed();
	}

	public void proceed() {
		System.out.println(
		        "AsyncRestTmpltNetty::proceed() started");
		try {
			AsyncClientHttpRequestFactory acrf = new Netty4ClientHttpRequestFactory();
			URI uri = new URI(
			        "http://localhost:8080/Example201726/time/30");
			AsyncClientHttpRequest asynReq = acrf
			        .createAsyncRequest(uri, HttpMethod.GET);
			ListenableFuture<ClientHttpResponse> future = asynReq
			        .executeAsync();
			ClientHttpResponse response = future.get();

			System.out.println(
			        IOUtils.toString(response.getBody()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println(
		        "AsyncRestTmpltNetty::proceed() ends");
	}
}

Tags:

by , on July 23rd, 2017

  • Categories