Netflix Ribbon

Ribbon is a client-side, load balancing solution that has a smooth integration with the Spring Cloud ecosystem. It can consume a service that is exposed using Eureka simply by specifying the service name. Since all the server instances are registered in Eureka, it will choose one of them to execute the request.

Let's say we have another service named cinema-service. Say that this service has an endpoint that can be used to query a cinema by its ID. As part of the cinema payload, we want to include all the movies that are available in the movies-service.

First of all, we need to add the following dependency:

compile('org.springframework.cloud:spring-cloud-starter-netflix-ribbon')

Then, as part of the application class, we need to create a new RestTemplate bean that will be injected in order to consume the services available in Eureka:

@EnableDiscoveryClient
@SpringBootApplication
public class CinemaServiceApplication
{
public static void main(String[] args)
{
SpringApplication.run(CinemaServiceApplication.class, args);
}
@LoadBalanced
@Bean
RestTemplate restTemplate()
{

return new RestTemplate();
}

}

The RestTemplate phrase is a client that is used to consume RESTful web services. It can execute a request against the movies-service as follows:

@RestController
public class CinemasController
{
private final CinemaRepository cinemaRepository;
private final RestTemplate restTemplate;
public CinemasController(CinemaRepository cinemaRepository,
RestTemplate restTemplate)
{
this.cinemaRepository = cinemaRepository;
this.restTemplate = restTemplate;
}
@GetMapping("/cinemas/{cinemaId}/movies")
public ResponseEntity<Cinema> queryCinemaMovies
(@PathVariable("cinemaId") Integer cinemaId)
{
Cinema cinema = cinemaRepository.findById(cinemaId).get();
Movie[] movies = restTemplate
.getForObject(
"http://movies-service/movies", Movie[].class);
cinema.setAvailableMovies(movies);
return new ResponseEntity<>(cinema, HttpStatus.OK);
}
}

Note how the service name is specified, and we don't have to provide any other information, such as the IP address or the port. This is good because it would be impossible to determine this information when new servers are being created and destroyed on demand.

..................Content has been hidden....................

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