Spring Cloud Netflix Ribbon

What is Ribbon?

Ribbon is a client-side load balancer that gives you a lot of control over the behavior of HTTP and TCP clients. Ribbon is aware of multiple instances of a service and chooses a particular instance of it. One advantage of this is client controls the load balancing algorithm.

Ribbon Works with Feign That we discussed in last post.

The Code for this post is available for download here.

Demo Application

Our Simple HelloService Returns String Hello Message From Server: {port_number}. We will launch multiple instance of HelloService. Our Ribbon Client will call HelloService in Round-Robin way.

HelloService
1
2
3
4
5
6
7
8
9
10
11
@RestController
@RequestMapping("/helloworld")
public class HelloController {
@Autowired
private Environment environment;
@GetMapping
public String getMessage() {
String port = environment.getProperty("local.server.port");
return "Hello Message From Server " + port;
}
}

Getting Started With Spring Cloud Netflix Ribbon

To include Ribbon in project We need to use artifact id spring-cloud-starter-netflix-ribbon

netflix-ribbon Maven
1
2
3
4
     <dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>

Update FeignClient to use Ribbon Load Balancing

FeignClient With Ribbon
1
2
3
4
5
6
7
@FeignClient(name = "hello", configuration = HelloClientConfig.class)
@RibbonClient(name = "hello")
public interface HelloClient {

@RequestMapping(method = RequestMethod.GET, value = "/helloworld")
String getMessage();
}

A central concept in Ribbon is that of the named client. We Provide the application name in
application.properties.
application-name.ribbon.listOfServers Property is used to provide list of Servers.

application.properties
1
2
spring.application.name=hello
hello.ribbon.listOfServers: localhost:8080,localhost:8081

Test Application

  1. Start HelloService on port 8080 and 8081.
  2. Start Client Application on 8083.
    Then Go to http://localhost:8083/ribbon-test-client/
    first time it should return message as “Hello Message From Server 8080” and next time as “Hello Message From Server 8081”

The Code for this post is available for download here.

Share Comments