springcloud的ribbon配置策略三种方式
解决方法:
1、全局
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RandomRule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RibbonConfiguration {
@Bean
public IRule ribbonRule() {
return new RandomRule();
}
}
2、注解
先自定义注解:
public @interface AvoidScan {}
策略配置类:
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.IRule;
import com.netflix.loadbalancer.RoundRobinRule;
import com.wlg.springcloud.eurekaclientribbon.AvoidScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;
@Configuration
@AvoidScan
public class RibbonConfiguration {
@Resource
private IClientConfig clientConfig;
@Bean
public IRule roundRobinRule(IClientConfig clientConfig) {
return new RoundRobinRule();
}
}
springboot启动类:
加@RibbonClient和@ComponentScan让spring 不去扫描被 @AvoidScan 注解注释的类,因为不能应用于全局,所以只对service-one服务实例生效
@SpringBootApplication
@EnableDiscoveryClient
@RibbonClient(name = "service-one",configuration = RibbonConfiguration.class)
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, value = {AvoidScan.class})})
public class EurekaClientRibbonApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaClientRibbonApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
如果有多个服务:
@RibbonClients(value = {
* @RibbonClient(name = "client-one, configuration = RibbonConfigurationOne.class),
* @RibbonClient(name = "client-two, configuration =RibbonConfigurationTwo.class)
* })
3、配置文件
在application.yml文件添加以下配置,service-one改成你的服务名:
server:
port: 9904
spring:
application:
name: service-four
eureka:
client:
serviceUrl:
defaultZone: http://localhost:9901/eureka/
instance:
prefer-ip-address: true
#针对 eureka-client-A 服务实例 使用 指定的随机策略./
service-one:
ribbon:
NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule