标签:author 本地 over tin auth 示例 out private http
实现思想:
负载均衡算法:请求书%服务器数量得到实际服务器下标HttpClient进行调用
利用DiscoveryClient
1.注入@Autowired
private DiscoveryClient discoveryClient
2.List<ServiceInstance> discoveryClientInstances = discoveryClient.getInstances("服务器别名"); //获得该别名集群的所有服务信息
计算:list下标 = 访问次数 % discoveryClientInstances.size()
假设 : 第一次访问 : 1(访问次数) % 2(有两个服务信息) = 访问下标1
第一次访问 : 2(访问次数) % 2(有两个服务信息) = 访问下标0
以此类推,获得服务器地址将进行轮询
源码示例:
/**
* @author fish
*/
@RestController
public class FishRibbonController {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
private int reqNub = 1;
@RequestMapping(value = "myRibbon")
public String myRibbon(){
String insAdd = serviceUri() + "/index";
System.out.println(insAdd);
return restTemplate.getForObject(insAdd,String.class);
}
public String serviceUri(){
List<ServiceInstance> discoveryClientInstances = discoveryClient.getInstances("provider");
if(discoveryClientInstances == null || discoveryClientInstances.size() == 0){
return null;
}
int instances = discoveryClientInstances.size();
int serviceIndex = reqNub % instances;
reqNub++;
return discoveryClientInstances.get(serviceIndex).getUri().toString();
}
}
手写类似Ribbon 实现本地负载均衡,so easy,一眼你就懂
标签:author 本地 over tin auth 示例 out private http
原文地址:https://www.cnblogs.com/fishness/p/12198082.html