RestTemplate in Spring Boot MicroService

Home / RestTemplate in Spring Boot MicroService

As we know in microservice architecture we have many independent application and some time it is needed that one application communicates with other application to do some operation. So if we want to communicate between two microservice then spring cloud provide us two useful Component

  1. RestTemplate
  2. Feign Client

In This Post we will discuss how two microservice communicate between them using RestTemplate. Make Sure you have your Eureka Server Running and both the application is registered on that. To use RestTemplate in our application we have to follow below steps:

  1. Add required dependeny in your pom.xml file.
  2. Create Two MicroService project. In this we create two project one is MicroService-1 and another is MicroService-2.
  3. Give ApplicationName , Port and Eureka server path in your application.properties file.
  4. Create a Bean for RestTemplate because we can’t auto-wired RestTemlate directly. So we create a configuration class and initialize a Bean for RestTemplate.
  5. Autowired RestTemplate in your Service class to call Rest End Point of another application.

Follow above Steps:

1- Add below dependency in your pom.xml file.

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.cloud</groupId>
 <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<dependency>
 <groupId>com.googlecode.json-simple</groupId>
 <artifactId>json-simple</artifactId>
 <version>1.1.1</version>
</dependency>

2- Now we are creating a project Name MicroService-1 and from here we call RestEndPoint of MicroService-2 application.

3- Add below property in your application.properties file.

spring.application.name=microservice-1
server.port=8081
eureka.client.service-url.default-zone=http://localhost:8761/eureka

4- Create a Bean for RestTemplate.

package com.javadream.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

@Configuration
public class Config {

	@Bean
	public RestTemplate template() {
		HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory();
		httpRequestFactory.setConnectionRequestTimeout(4000);
		httpRequestFactory.setConnectTimeout(4000);
		httpRequestFactory.setReadTimeout(4000);
		return new RestTemplate(httpRequestFactory);
	}
}

5- Now create a Controller class autowired RestTemplate inside that and call RestEndPoint of MicroService-2 application.

For Calling a Get Request of MicroService-2 we use below syntax:

String responseFromMS2 = restTemplate.getForObject("http://localhost:8082/student/showAllStudent",
					String.class);

For Calling a Post Request of MicroService-2 we use below syntax:

HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		JSONObject studentObj = new JSONObject();
		studentObj.put("rollNo", 199);
		studentObj.put("name", "New_Student");
		studentObj.put("email", "new.student@gmail.com");
		org.springframework.http.HttpEntity<String> s = new org.springframework.http.HttpEntity<String>(studentObj.toString(),headers);
		String postForObject = restTemplate.postForObject("http://localhost:8082/student/addStudent", s, String.class);

Complete Code For Calling Get and Post EndPoint of MicroService-2 application:

package com.javadream.controller;

import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("/restTemplateDemo")
public class RestTemplateDemoController {

	private static final Logger logger = LoggerFactory.getLogger(RestTemplateDemoController.class);
	private final String GLOBAL_ERROR = "Some technical Error Please try again after some time";

	@Autowired
	private RestTemplate restTemplate;

	@GetMapping("call_MS2_showAllStudent_endPoint")
	public String callMicroservice_2_ShowAllStudent() {
		try {
			String responseFromMS2 = restTemplate.getForObject("http://localhost:8082/student/showAllStudent",
					String.class);
			logger.info("vvv::  responseFromMS2= " + responseFromMS2);
			return responseFromMS2;
		} catch (Exception e) {
			e.printStackTrace();
			return GLOBAL_ERROR;
		}
	}
	
	@GetMapping("call_MS2_addStudent_endPoint")
	public String call_MS_2_addStudent_endPoint() {
		HttpHeaders headers = new HttpHeaders();
	      headers.setContentType(MediaType.APPLICATION_JSON);
		JSONObject studentObj = new JSONObject();
		studentObj.put("rollNo", 199);
		studentObj.put("name", "New_Student");
		studentObj.put("email", "new.student@gmail.com");
		org.springframework.http.HttpEntity<String> s = new org.springframework.http.HttpEntity<String>(studentObj.toString(),headers);
		String postForObject = restTemplate.postForObject("http://localhost:8082/student/addStudent", s, String.class);
		return postForObject;
	}
	
	
}

Complete Code on GitHub : RestTemplate in Spring Cloud

You may also like:

Spring boot security using JWT ( JSON WEB TOKENS ).

How to deploy spring boot application on docker 

Spring Boot with Apache kafka.

Swagger2 in Spring Boot

Create WAR of Spring Boot Project

Help Others, Please Share

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

x