Let's set up another simple microservice to consume the random service exposed by Microservice A. Let's use Spring Initializr (https://start.spring.io) to initialize the microservice, as shown in the following screenshot:
Let's add the service to consume random service:
@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;
}
}
Important things to note are as follows:
- @Value("${number.service.url}") private String numberServiceUrl: We would want the number service URL to be configurable in application properties.
- @RequestMapping("/add") public Long add(): Exposes a service at the URI /add. The add method calls the number service using RestTemplate and has the logic to sum the numbers 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
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
When the service is called at the URL http://localhost:8100/add, the following response is returned:
2890
The following is an extract from the log of Microservice A:
c.m.s.c.c.RandomNumberController : Returning [752,
119, 493, 871, 445]
The log shows that random service from Microservice A returned 5 numbers. The add service in the service consumer added them up and returned a result 2890.
We now have our example microservices ready. In the next steps, we will add Cloud-Native features to these microservices.