上篇文章我们已经完成了Ribbon负载均衡的功能。做法很简单,只需要在RestTemplate添加@LoanBalanced 的注解。默认情况下,Ribbon的负载均衡策略是RoundRobbin(轮训)的方式,可很多时候在特定场景下需要不同的策略,这个时候就需要自定义Ribbon策略了。看下面代码:
[java] view plain copy
- package com.zhuyang.cloud.controller;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.cloud.client.loadbalancer.LoadBalanced;
- import org.springframework.cloud.netflix.ribbon.RibbonClient;
- import org.springframework.context.annotation.Bean;
- import org.springframework.web.bind.annotation.PathVariable;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RestController;
- import org.springframework.web.client.RestTemplate;
- import com.zhuyang.cloud.entity.User;
- import com.zhuyang.config.RibbonConfiguration;
- @RestController
- @RibbonClient(name = "microservice-provider", configuration = RibbonConfiguration.class)//name是provider的服务名 <span style="font-family: Arial, Helvetica, sans-serif;">RibbonConfiguration为自定义配置</span>
- public class MovieController {
- @Bean
- @LoadBalanced
- public RestTemplate restTemplate() { // equals to RestTemplate
- // restTemplate=new RestTemplate();
- return new RestTemplate();
- }
- @Autowired
- private RestTemplate restTemplate;
- @RequestMapping(value = "/movie/{id}", method = RequestMethod.GET)
- public User findById(@PathVariable Long id) {
- // return restTemplate.getForEntity("http://localhost:8000/service/"+id,
- // User.class).getBody();
- return restTemplate.getForEntity("http://microservice-provider/provider/service/" + id, User.class).getBody();
- }
- }
[html] view plain copy
- server:
- port: 8001
- eureka:
- client:
- serviceUrl:
- defaultZone: http://user:[email protected]:8761/eureka/ # 指定注册中心的地址
- instance:
- preferIpAddress: true
- spring:
- application:
- name: microservice-consumer
- microservice-provider: ##config ribbon
- ribbon:
- eureka:
- enabled: false
- listOfServers: localhost:8000, localhost:8002,localhost:8003 ##假设provider有3台instance端口分别是8000 8002 8003
- ServerListRefreshInterval: 15000
[java] view plain copy
- package com.zhuyang.config;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Bean;
- import com.netflix.client.config.IClientConfig;
- import com.netflix.loadbalancer.IPing;
- import com.netflix.loadbalancer.IRule;
- import com.netflix.loadbalancer.PingUrl;
- import com.netflix.loadbalancer.ZoneAvoidanceRule;
- public class RibbonConfiguration {
- @Autowired
- private IClientConfig ribbonClientConfig;
- @Bean
- public IPing ribbonPing(IClientConfig config) {
- // ping url will try to access http://microservice-provider/provider/ to
- // see if reponse code is 200 . check PingUrl.isAlive()
- // param /provider/ is the context-path of provider service
- return new PingUrl(false, "/provider/");
- }
- @Bean
- public IRule ribbonRule(IClientConfig config) {
- // return new AvailabilityFilteringRule();
- return new RandomRule();//
- // return new BestAvailableRule();
- // return new RoundRobinRule();//轮询
- // return new WeightedResponseTimeRule();
- // return new RetryRule();
- // return new ZoneAvoidanceRule();
- }
- }
在RibbonConfiguration中的ribbonRule方法就是用来定义不用的策略,每种策略所对应的实现类和描述 都已经添加了注释。例如我们返回的是RandomRule策略,那么我们在多次请求provider的时候就不再是轮训的方式进行命中,而是随机方式。。下面是RandomRule的代码实现
[java] view plain copy
- public Server choose(ILoadBalancer lb, Object key) {
- if (lb == null) {
- return null;
- }
- Server server = null;
- while (server == null) {
- if (Thread.interrupted()) {
- return null;
- }
- List<Server> upList = lb.getReachableServers();//get all reachable server .list listOfServers: localhost:8000, localhost:8002,localhost:8003
- List<Server> allList = lb.getAllServers();
- int serverCount = allList.size();
- if (serverCount == 0) {
- return null;
- }
- int index = rand.nextInt(serverCount);//get random index
- server = upList.get(index);//get specified server eg:<span style="font-family: Arial, Helvetica, sans-serif;">localhost:8000</span>
- if (server == null) {
- Thread.yield();
- continue;
- }
- if (server.isAlive()) {
- return (server);
- }
- // Shouldn't actually happen.. but must be transient or a bug.
- server = null;
- Thread.yield();
- }
- return server;//return selected server
- }