Implementing Ribbon in the Service Consumer microservice

We will add Ribbon to the Service Consumer microservice. This microservice will distribute the load among two instances of Microservice A.

Let's start by adding the Ribbon dependency to the pom.xml file of the Service Consumer microservice:

    <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

Next, we can configure the URLs for the different instances of Microservice A. Add the following configuration to application.properties in the Service Consumer microservice:

    microservice-a.ribbon.listOfServers= http://localhost:8080,http://localhost:8081

We will then specify the @RibbonClient annotation on the service proxy—microservice-a in this example. The @RibbonClient annotation is used to specify a declarative configuration for a Ribbon client:

    @FeignClient(name ="microservice-a")
@RibbonClient(name="microservice-a")
public interface RandomServiceProxy {

When you restart the Service Consumer microservice and hit the add service at http://localhost:8100/add, you will get the following response:

    2705

This request is handled by an instance of Microservice A running on port 8080. An extract from the log is shown here:

    c.m.s.c.c.RandomNumberController : Returning [487,
441, 407, 563, 807]

When we hit the add service again at the same URL, http://localhost:8100/add, we get the following response:

    3423

However, this time, the request is handled by an instance of Microservice A running on port 8081. An extract from the log is shown here:

    c.m.s.c.c.RandomNumberController : Returning [661,
520, 256, 988, 998]

We have now successfully distributed the load among the different instances of Microservice A. While this can be improved further, this is a good start.

While round robin (RoundRobinRule) is the default algorithm that's used by Ribbon, there are other options available:

  • AvailabilityFilteringRule will skip servers that are down and that have a number of concurrent connections.
  • WeightedResponseTimeRule will pick the server based on the response times. If a server takes a long time to respond, it will get fewer requests.

The algorithm to be used can be specified in the application configuration:

    microservice-a.ribbon.NFLoadBalancerRuleClassName = 
com.netflix.loadbalancer.WeightedResponseTimeRule

microservice-a is the name of the service we specified in the @RibbonClient(name="microservice-a") annotation.

The following diagram shows the architecture for the components we have set up already:

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

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