Ribbon for load balancing

Running an instance of the microservice, the URL is hardcoded in the client, and in the service-to-service calls. In reality, this approach does not

Well, because there can be multiple instances of the service, in this case, we should use a load balancer or a local DNS server to abstract

Instead of the location of the actual instance, the one configured in the client should be an alias or the address of the load balancer. load balancer

After receiving the alias, resolve it into one of the available instances. In this way we can configure many instances and it also helps with processing

The server fails the problem, which is transparent to the client.

 

The above ideas can be implemented with Spring Cloud Netflix Ribbon. Ribbon is a client load balancer,

It can perform round-robin load balancing on a group of servers. The Ribbon library can also have other load balancing algorithms.

 

Spring Cloud provides a declarative way to configure and use Ribbon clients.



 

 

As shown in the figure above, the Ribbon client obtains a list of all available microservice instances from the Config server, and, by default, uses

round-robin load balancing algorithm.

 

In order to use the Ribbon client, add the following maven dependencies:

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

 

Modify the Booking microservice configuration file, booking-service.properties, and add a new property to configure

A set of Fare microservices:

fares-proxy.ribbon.listOfServers=localhost:8080,localhost:8081

 

At this point, the original FareServiceProxy class needs to be modified in order to use the Ribbon client, noting the original @RequestMapping

The value in the need to be changed from /get to /fares/get, so that it is easy to move the host name and port into the configuration file:

@FeignClient(name="fares-proxy")
@RibbonClient(name="fares")
public interface FareServiceProxy {
  @RequestMapping(value = "fares/get", method=RequestMethod.GET)

 

 

At this point, we can run 2 Fares microservice instances, one on 8080 and one on 8081:

java -jar -Dserver.port=8080 fares-1.0.jar
java -jar -Dserver.port=8081 fares-1.0.jar

 

Run the Booking microservice, and when it starts, its CommandLineRunner will automatically insert a booking record, which will go

first server.

 

When running the website project, it calls the Booking service, and the request goes to the second server.


 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326138911&siteId=291194637