Ribbon 负载均衡
首先引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
修改application类,加入
@LoadBalanced
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
controller类中调用
@Autowired
private RestTemplate restTemplate;
@GetMapping("user")
@ResponseBody
public List<User> findAll() {
List<User> users = restTemplate.getForObject("http://USER/findAll",List.class);
return users;
}
yml可选配置参数
#预加载配置,默认为懒加载
ribbon:
eager-load:
enabled: true
clients: mima-cloud-producer,mima-cloud-producer2
#这里使用服务提供者的instanceName
mima-cloud-producer:
ribbon:
# 代表Ribbon使用的负载均衡策略
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
# 每台服务器最多重试次数,但是首次调用不包括在内, Max number of retries on the same server (excluding the first try)
MaxAutoRetries: 1
# 最多重试多少台服务器,Max number of next servers to retry (excluding the first server)
MaxAutoRetriesNextServer: 1
# 无论是请求超时或者socket read timeout都进行重试,Whether all operations can be retried for this client
OkToRetryOnAllOperations: true
# Interval to refresh the server list from the source
ServerListRefreshInterval: 2000
# Connect timeout used by Apache HttpClient
ConnectTimeout: 3000
# Read timeout used by Apache HttpClient
ReadTimeout: 3000
mima-cloud-producer2:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.ZoneAvoidanceRule