Creating the method to consume the random list service (from Microservice A)

We want the Service Consumer microservice to invoke the service exposed from Microservice A—a random list service. The business logic we will implement in Service Consumer is to take the list of random numbers that are returned from Microservice A and add them up.

A simple implementation using RestTemplate is shown here:

@RestController
public class NumberAdderController {

private Log log = LogFactory.getLog(NumberAdderController.class);

@Value("${number.service.url}")
private String numberServiceUrl;

@RequestMapping("/add")
public Long add() {
long sum = 0;

ResponseEntity<Integer[]> responseEntity
= new RestTemplate()
.getForEntity(numberServiceUrl, Integer[].class);

Integer[] numbers = responseEntity.getBody();

for (int number : numbers) {
sum += number;
}

log.warn("Returning " + sum);

return sum;
}
}

Some important things to note are as follows:

  • @Value("${number.service.url}") private String numberServiceUrl: We want the number service URL to be configurable in application properties.
  • @RequestMapping("/add") public Long add(): This exposes a service at the URI, that is, /add. The add method calls the number service using RestTemplate and has the logic to sum the numbers that are returned in the response.

Let's configure application.properties, as shown in the following snippet:

    spring.application.name=service-consumer
server.port=8100
number.service.url=http://localhost:8080/random

Some important things to note are as follows:

  • spring.application.name=service-consumer: Configures a name for the Spring Boot application
  • server.port=8100: Uses 8100 as the port for service consumer
  • number.service.url=http://localhost:8080/random: Configures the number service URL for use in the add service
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset