定制化开发是一个用于负载均衡的组件
配置
导入依赖
要导入netflix-ribbon的依赖,springcloud-ribbon定制化开发的依赖可能会出现版本不匹配的问题
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
- <version>2.2.10.RELEASE</version>
- </dependency>
在配置的模块启动类中注入bean
- @Bean
- @LoadBalanced
- public RestTemplate restTemplate(){
- return new RestTemplate();
- }
将gateway的路由uri地址http://127.0.0.1:8080 (图2) 改成成下面的服务名demoA (图1) 进行
(图1)对服务进行配置,两个不同端口的服务共用同一个服务名demoA
路径端口:localhost:8081,localhost:8082
负载均衡策略:
轮询:RoundRobinRule
权重轮询:WeightedResponseTimeRule
随机:RandomRule
最少并发数:BestAvailableRule
以上为基本策略可以自行查询了解。
- ribbon:
- eager-load:
- enabled: false
- clients: demo,demo1,demo2
- demoA:
- ribbon:
- # 负载地址
- listOfServers: localhost:8081,localhost:8082
- # 代表Ribbon使用的负载均衡策略
- NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RoundRobinRule
- # 每台服务器最多重试次数,但是首次调用不包括在内
- MaxAutoRetries: 1
- # 最多重试多少台服务器
- MaxAutoRetriesNextServer: 1
- # 无论是请求超时或者socket read timeout都进行重试
- OkToRetryOnAllOperations: true
( 图 1 )
( 图 2 )