woshikid / blog

Apache License 2.0
8 stars 1 forks source link

Ribbon学习笔记 #172

Open woshikid opened 2 years ago

woshikid commented 2 years ago

POM

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    <version>2.2.10.RELEASE</version>
</dependency>

自定义服务列表

test: # springApplicationName
  ribbon:
    listOfServers: http://server1,http://server2 # 服务列表

自动获取服务列表(依赖注册中心) 需要降级Spring Cloud

<!-- 对应Spring Boot为2.3.12.RELEASE -->
<spring-cloud.version>Hoxton.SR12</spring-cloud.version>

使用Ribbon

@Autowired
private LoadBalancerClient loadBalancerClient;

ServiceInstance serviceInstance = loadBalancerClient.choose(springApplicationName);
String url = serviceInstance.getUri().toString();

注入RestTemplate

@Bean
@LoadBalanced
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder
        .setConnectTimeout(Duration.ofMillis(1000)) // 连接超时
        .setReadTimeout(Duration.ofMillis(1000)) // 请求超时
        .build();
}

String response = restTemplate.getForObject("http://%s/test".formatted(springApplicationName), String.class);

RestTemplate自动重试(依赖Spring Retry) 需要降级Spring Cloud,同上 默认配置

ribbon: # 全局配置
  #ConnectTimeout: 1000 # 连接超时,对RestTemplate无效
  #ReadTimeout: 1000 # 请求超时,对RestTemplate无效
  NFLoadBalancerRuleClassName: com.netflix.loadbalancer.ZoneAvoidanceRule # 底层为RoundRobinRule
  MaxAutoRetries: 0 # 当前服务器重试次数
  MaxAutoRetriesNextServer: 1 # 尝试切换服务器次数
  OkToRetryOnAllOperations: false # 重试非GET请求
  retryableStatusCodes: "" # 默认404,500都不重试

积极加载

ribbon:
  eager-load:
    enabled: true
    clients: test,test2 # springApplicationName