0
0
Spring Bootframework~5 mins

Service-to-service communication in Spring Boot

Choose your learning style9 modes available
Introduction

Service-to-service communication lets different parts of an app talk to each other. This helps them work together smoothly.

When one microservice needs data from another microservice.
When you want to split a big app into smaller, focused services.
When services need to share updates or trigger actions in each other.
When building scalable apps that can grow by adding more services.
Syntax
Spring Boot
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject("http://service-url/api/data", String.class);
RestTemplate is a simple way to call other services using HTTP.
Spring Boot also supports WebClient for reactive calls.
Examples
Calls another service at localhost on port 8081 and gets a message as a string.
Spring Boot
RestTemplate restTemplate = new RestTemplate();
String result = restTemplate.getForObject("http://localhost:8081/api/message", String.class);
Uses WebClient for a blocking call to get a message from another service.
Spring Boot
WebClient webClient = WebClient.create("http://localhost:8081");
String result = webClient.get().uri("/api/message").retrieve().bodyToMono(String.class).block();
Sample Program

This Spring Boot app has two controllers. One acts as a service returning a message. The other calls that service using RestTemplate and returns the message it got.

Spring Boot
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

@RestController
class ClientController {

    private final RestTemplate restTemplate = new RestTemplate();

    @GetMapping("/call-service")
    public String callService() {
        String url = "http://localhost:8081/api/message";
        return restTemplate.getForObject(url, String.class);
    }
}

@RestController
class ServiceController {

    @GetMapping("/api/message")
    public String getMessage() {
        return "Hello from Service!";
    }
}
OutputSuccess
Important Notes

Make sure the service you call is running and accessible at the URL you use.

Use environment variables or config files to store service URLs, not hard-coded strings.

For better performance and features, consider using WebClient instead of RestTemplate in new projects.

Summary

Service-to-service communication helps microservices work together.

RestTemplate and WebClient are common ways to call other services in Spring Boot.

Always handle errors and timeouts when calling other services.