当前位置:网站首页>Using ribbon to realize client load balancing
Using ribbon to realize client load balancing
2022-06-11 10:37:00 【chentian114】
Use Ribbon Achieve client load balancing
List of articles
Preface
In the foreword 《 Use Eureka Provide service registration and discovery 》https://mp.weixin.qq.com/s/L2Tx6Lk0jl6GW-g0SeUXyw in , Based on Eureka Realize service registration and discovery . Generally speaking , In the production environment , Each micro service will deploy multiple instances , So how do service consumers allocate requests to multiple service provider instances ?
stay Spring Cloud in , When Ribbon and Eureka When used in combination ,Ribbon Can be automatically from Eureka Server Gets a list of service provider addresses , And based on the load balancing algorithm , Request one of the service provider instances .
Ribbon brief introduction
Ribbon yes Netflix Published load balancer , It helps control HTTP and TCP The behavior of the client . by Ribbon After configuring the service provider address list , Ribbon Can be based on some kind of load balancing algorithm , Automatically help service consumers to request . Ribbon Many load balancing algorithms are provided by default , For example, polling 、 Random etc. . Of course , We can also do Ribbon Implement custom load balancing algorithm .

Integrate for service consumers Ribbon
Create project , Copy project micro-consumer-movie , take artifactId It is amended as follows micro-consumer-movie-ribbon .
Introduce... For the project Ribbon Dependence ,spring-cloud-starter-eureka Included by default Ribbon Dependence spring-cloud-starter-ribbon .
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
- by RestTemplate add to
@LoadBalanceannotation , Can be RestTemplate Integrate Ribbon , Make it load balanced .
@Configuration
public class RestConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
- start-up Eureka Server Registry Center and Multiple service providers micro-provider-user .
java -jar micro-discovery-eureka-0.0.1-SNAPSHOT.jar
java -jar micro-provider-user-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar micro-provider-user-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
- Modify the request address of the service consumer calling the service provider ,http://localhost:8000/ Change it to http://micro-provider-user/ .
@RestController
@RequestMapping("/movie/v1")
public class MovieController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
private RestTemplate restTemplate;
@Resource
private LoadBalancerClient loadBalancerClient;
@GetMapping("/{id}")
public User findById(@PathVariable Long id){
User entity = restTemplate.getForObject("http://micro-provider-user/user/v1/"+id, User.class);
return entity;
}
@GetMapping("/log-instance")
public void logUserInstance(){
ServiceInstance serviceInstance = loadBalancerClient.choose("micro-provider-user");
logger.info("{}:{}:{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
}
}
micro-provider-user Is the virtual host name of the user microservice (virtual host name), When Ribbon and Eureka When used in combination , The virtual host name will be automatically mapped to the network address of the microservice .
By default , The virtual host name is consistent with the service name . Of course , You can also use configuration properties eureka.instance.virtual-host-name or eureka.instance.secure-virtual-host-name Specify the virtual host name .
- Start the service consumer service micro-consumer-movie-ribbon , test Ribbon , Multiple access http://localhost:8010/movie/v1/1 , It can be found that the requests are evenly distributed to the two user microservice nodes , It shows that load balancing has been realized .
visit http://localhost:8010/movie/v1/log-instance , logUserInstance() Method used in LoadBalancerClient Of API Get the currently selected user microservice node more intuitively .
Use properties to customize Ribbon To configure
Ribbon Support the use of custom attributes , The supported properties are as follows :
- NFLoadBalancerClassName : To configure ILoadBalancer Implementation class of
- NFLoadBalancerRuleClassName : To configure IRule Implementation class of .
- NFLoadBalancerPingClassName : To configure IPing Implementation class of .
- NIWSServerListClassName : To configure ServerList Implementation class of .
- NIWSServerListFilterClassName : To configure ServerListFilter Implementation class of .
practice : Modify by attributes Ribbon Client Load balancing rules of .
Copy project micro-consumer-movie-ribbon , take ArtifactId It is amended as follows micro-consumer-movie-ribbon-custom-props .
modify application.yml , Name it micro-provider-user Of Ribbon Client The load balancing rule of is set to random :
micro-provider-user:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
- Start the service micro-consumer-movie-ribbon-custom-props , test http://localhost:8010/movie/v1/log-instance , Check the log , You will find that the requests will be randomly distributed to two user microservice nodes .
Out of the Eureka Use Ribbon
In reality, some micro services may not be registered to Eureka Server On , To use Ribbon Load balancing , What to do ?

Copy project micro-consumer-movie-ribbon , take ArtifactId It is amended as follows micro-consumer-movie-ribbon-without-eureka .
Delete eureka Dependence spring-cloud-starter-eureka , And add Ribbon rely on
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-ribbon</artifactId>
</dependency>
Remove the on the startup class
@EnableDiscoveryClientannotation .Modify the configuration application.yml , by micro-provider-user Set up Ribbon The client sets the requested address list :
server:
port: 8010
spring:
application:
name: micro-consumer-movie
micro-provider-user:
ribbon:
listOfServers: localhost:8000,localhost:8001
- Start multiple service providers micro-provider-user .
java -jar micro-provider-user-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer1
java -jar micro-provider-user-0.0.1-SNAPSHOT.jar --spring.profiles.active=peer2
- Start the service micro-consumer-movie-ribbon-without-eureka , test http://localhost:8010/movie/v1/2 or http://localhost:8010/movie/v1/log-instance .
From the results , Although the movie microservices and user microservices are not registered at this time Eureka On , Ribbon Still working , The request will still be allocated to two user microservice nodes .
Hunger is loaded
Spring Cloud For each name Ribbon Client Maintain a sub application context , This context is lazy loaded by default . Of a given name Ribbon Client On the first request , The corresponding context will be loaded , therefore , First requests tend to be slow .
from Spring Cloud Dalston Start , We can configure starvation loading . for example
ribbon:
eager-load:
enabled: true
clients: client1,client2
such , For the name client1 , clent2 Of Ribbon Client , The corresponding sub application context will be loaded at startup , from And improve the access speed of the first request .
Code warehouse
https://gitee.com/chentian114/spring-cloud-practice
official account
Reference resources
《Spring Cloud And Docker Microservice architecture practice 》 Zhou Li
边栏推荐
- 数字藏品app系统源码
- 班组级安全培训,新员工入职培训教育课件,全内容PPT套用
- Some understanding of inductive bias
- 利用PHP开发的一款万能、表白墙系统部分代码片段
- Preview component packaging graphic tutorial in cadence OrCAD capture schematic design interface
- Leetcode 1961. Check whether the string is an array prefix
- NGUI,地图放大缩小
- 【Objective-C】‘NSAutoreleasePool‘ is unavailable: not available in automatic reference counting mode
- [Objective-C] differences between structs and classes
- Xilinx pin constraint file xdc
猜你喜欢

Pyramidtnt: TNT with characteristic pyramid structure

Tiktok encounters cultural conflict in the UK, and many employees leave in a short time

Bcgcontrolbar Library Professional Edition, fully documented MFC extension class

白屏时间、首屏时间

Installing mysql5.7 for Linux

详述用网络分析仪测量DC-DC和PDN

以银行异业合作为例,浅谈小程序生态的建设

Leetcode 1952. Triple divisor

国际多语言出海商城返佣产品自动匹配订单源码

Internet of things security in the era of remote work
随机推荐
Source code of digital collection app system
NewOJ Week 2---BCD
批量对数据添加噪声并生成新命名标注文件
Puppeter class of puppeter introduction
Waiting event enq: Ko - some feasible processing methods for fast object checkpoint
Preview component packaging graphic tutorial in cadence OrCAD capture schematic design interface
电子设备辐射EMC整改案例
Internet of things security in the era of remote work
MySQL foundation part common constraints summary part 2
修复UICollectionView 没有到达底部安全区的问题
MOSFET的SOA或者ASO是什么?
云画质助手iApp源码
使用 Feign 实现声明式 REST 调用
Correct opening method of RPC | understand go native net/rpc package
GameFi:您需要了解的关于“即玩即赚”游戏经济的一切
使用bat向文件的第一行中写入内容
&lt; Pytorch series 4 & gt;: Constructing neural network model
【CV基础】颜色:RGB/HSV/Lab
Streaming computing knowledge
minIni移植到littlefs