Tuesday, June 3, 2025

MS - Call rest service to service call Step1; Call with Simple RestTemplate

 1. Create Service - greet-service with simple message returning service call.

2. Make another service - rest-client and call greet-service

Steps: 

2.1 Create Controller 

2.2 Make ResTemplate object

2.3 using restTemplate object call rest-service eg:greet-service withfindObject

Dependencies

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

Appication Properties

spring.application.name=greet-service
server.port=8090

Below are the code blocks

Greet class

public class Greet {

public Greet(String message) {
this.message = message;
}

private String message;

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}
}


@RestController
public class GreetController {

private String message = "Demo with RestTemplate";

@RequestMapping("/greet")
public Greet greet() {

return new Greet(message);
}
}


2. Make another service - rest-client and call greet-service

Below are code blocks

spring.application.name=rest-client
server.port=8095


package com.example.rest_client.controller;

import com.example.rest_client.model.Greet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class GreetClientController {

private RestTemplate restTemplate = new RestTemplate();
// @Autowired
// private RestTemplate restTemplate;

@RequestMapping("/greet-call")
Greet greet() {
//Phase 1 - without Discovery/Eureka client
Greet greet = restTemplate.getForObject("http://localhost:8090/greet", Greet.class);
//With Discovery client - Now we can use service name - and with other option available via eureka server
// you need to configure DiscoveryClient - else cannot find hte hostname "greet-service" which is registered inEureka server
// Greet greet = restTemplate.getForObject("http://greet-service/greet", Greet.class);
return greet;
}
}



No comments:

Post a Comment