在消费中pom中引入
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
请求调用加+ @LoadBalanced 注解
进行服务调用
默认负载均衡是轮训模式
想要切换为随机模式需要重写restTemplate
@Configuration
@LoadBalancerClient(
//下面的value值大小写一定要和consul**里面的名字一样,必须一样value = "cloud-payment-service" ,configuration = RestTemplateConfig.class)
public classRestTemplateConfig
{
@Bean
@LoadBalanced //使用@LoadBalanced注解赋予RestTemplate**负载均衡的能力
publicRestTemplate restTemplate(){
return newRestTemplate();
}@Bean
ReactorLoadBalancer<ServiceInstance> randomLoadBalancer(Environment environment,
LoadBalancerClientFactory loadBalancerClientFactory) {
String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);return newRandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class), name);
}
}