您的位置:首页 > 编程语言 > Java开发

SpringCloud五:自定义配置Ribbon负载均衡策略

2018-11-19 16:59 621 查看

Ribbon的默认负载均衡策略是轮询,为了满足不同的需求,ribbon也为我们定义好了多种不同的策略,我们可以根据自己的需求自定义配置对应的策略。

Ribbon的核心是IRule,它是所有负载均衡算法的顶级接口。

 

详细的配置及POM请看上一章https://blog.csdn.net/qq331709114/article/details/84025970

第一种:通过注解方式

 1,创建一个Ribbon配置类

[code]@Configuration
public class RibbonConfiguration {

@Bean
public IRule ribbonRule(){
//return new RoundRobinRule();//轮询
//return new RetryRule();//重试
return new RandomRule();随机
}
}

注:

@Configuration配置的类不可以放到@ComponentScan所扫描的包下,@SpringBootApplication包含了@ComponentScan,所以@Configuration也不可以在@SpringBootApplication所扫描的包下。

把配置类放到启动类的上一级,这样就不会被@ComponentScan所扫描到

 

 在启动类加上@RibbonClient(name = "eureka-service",configuration = RibbonConfiguration.class)

configuration 对应的是Ribbon的配置类

[code]
//可以是其他的注册中心 如:zookeeper,
//@EnableDiscoveryClient
//注册中心必须是eureka
@EnableEurekaClient
@SpringBootApplication
@RibbonClient(name = "eureka-service",configuration = RibbonConfiguration.class)
public class RibbonApplication {

public static void main(String[] args) {
SpringApplication.run(RibbonApplication.class, args);
}

@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return  new RestTemplate();
}
}

再写一个测试接口

[code]    @Autowired
private LoadBalancerClient loadBalancerClient;

@GetMapping("loadBalancer")
public String loadBalancer(){                                        //必须是服务ID
ServiceInstance ServiceInstance = this.loadBalancerClient.choose("eureka-service");
log.info("{}:{}",ServiceInstance.getServiceId(),ServiceInstance.getPort());
return ServiceInstance.getServiceId()+":"+ServiceInstance.getPort();
}

重启服务后调用http://localhost:8764/loadBalancer,Ribbon开始随机消费。

第一种:通过配置文件的方式

只需要一条添加配置即可  

服务提供者的服务id.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

[code]#自定义负载均衡策略
#服务提供者的服务id.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule
eureka-service.ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule

再次调用http://localhost:8764/loadBalancer,同样进行了随机消费。

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: