Ribbon with Spring Cloud

Spring Cloud simplifies the use of Ribbon. The application has to be annotated with @RibbonClient. While doing so, a name for the application can be defined. In addition, the application needs to have a dependency on spring-cloud-starter- ribbon. In that case an instance of a microservice can be accessed using code like that in Listing 13.10. For that purpose, the code uses the Eureka name of the microservice.

Listing 13.10 Determining a Server with Ribbon Load Balancing

Servicelnstance instance = loadBalancer.choose("CATALOG");

String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/catalog/";

The use can also be transparent to a large extent. To illustrate this Listing 13.11 shows the use of RestTemplates with Ribbon. This is a Spring class, which can be used to call REST services. In the Listing the RestTemplate of Spring is injected into the object as it is annotated with @Autowired. The call in callMicroservice() looks like it is contacting a server called “stores.” In reality this name is used to search a server at Eureka, and the REST call is sent to this server. This is done via Ribbon so that the load is also distributed across the available servers.

Listing 13.11 Using Ribbon with RestTemplate

@RibbonClient(name = "ribbonApp")

... // Left out other Spring Cloud / Boot Annotations public class RibbonApp {

@Autowired

private RestTemplate restTemplate;

public void callMicroservice() {

Store store = restTemplate. getForOb]ect("http://stores/store/1", Store.class);

} }

Try and Experiment

• Load Balance to an Additional Service Instance

The “Order” microservice distributes the load onto several instances of the “Customer and Catalog” microservice—if several instances exist. Without further measures, only a single instance is started. The “Order” microservice shows in the log which “Catalog” or “Customer” microservice it contacts. Initiate an order and observe which services are contacted.

Afterwards start an additional “Catalog” microservice. You can do that using the command: docker run -v /microservice-demo:/microservice- demo —link eureka: eureka catalog-app in Vagrant. For Docker Compose docker-compose scale catalog=2 should be enough. Verify whether the container is running and observe the log output.

For reference: “Try and Experiment” in section 13.4 shows the main commands for using Docker. Section 13.7 shows how to use Docker Compose.

• Create Data

Create a new dataset with a new item. Is the item always displayed in the selection of items? Hint: The database runs within the process of the microservice—that is, each microservice instance possesses its own database.

 
Source
< Prev   CONTENTS   Source   Next >