SpringCloudカスタマイズRibbonクライアント負荷分散ポリシー
3940 ワード
RibbonのEurekaでの使用
依存の追加
ribbonの使用には2つの方法があり、注釈方式とプロファイル方式を使用しています.以下、順に紹介します.
注記モード
@SpringBootApplication
@EnableEurekaClient
@RibbonClient(name = "microservice-provider", configuration = TestConfiguration.class)
@ComponentScan(excludeFilters = { @ComponentScan.Filter(type = FilterType.ANNOTATION, value = ExcludeFromComponentScan.class) })
public class MicroserviceConsumerApplication {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerApplication.class, args);
}
}
@Configuration
@ExcludeFromComponentScan
public class TestConfiguration {
// @Autowired
// IClientConfig config;
@Bean
public IRule ribbonRule() {
return new RandomRule();
}
}
public @interface ExcludeFromComponentScan {
}
説明:
# .ribbon.NFLoadBalancerRuleClassName:
microservice-provider:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
@RibbonClients(value = {
@RibbonClient(name = "xxx",configuration = xxxConfiguration.class),
@RibbonClient(name = "microservice-provider",configuration = TestConfiguration.class)
})
使用例:
@RestController
public class MovieController {
@Autowired
private LoadBalancerClient loadBalancerClient;
// 。
@Autowired
private RestTemplate restTemplate;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
// ribbon , HTTP , user.class
return this.restTemplate.getForObject("http://microservice-provider/simple/" + id, User.class);
}
@GetMapping("/test")
public String test() {
// 。
ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider");
System.out.println("111" + ":" + serviceInstance.getServiceId() + ":" + serviceInstance.getHost() + ":" + serviceInstance.getPort());
return "1";
}
}
独立してribbonを使用
1.eurekaを導入した場合
ribbon:
eureka:
enabled: false
microservice-provider:
ribbon:
listOfServers: localhost:7900
2.eurekaを導入しなかった場合
org.springframework.cloud
spring-cloud-starter-ribbon
/dependency>
microservice-provider:
ribbon:
listOfServers: localhost:7900