Ribbon软负载均衡,与RestTempltete使用案例: @Configuration public class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplet(){ return new RestTemplate(); } } @Resource private RestTemplate restTemplate; @GetMapping("/consumer/paymentzk") public String payMentInfo(){ String result=restTemplate.getForObject(url+"/payment/paymentzk",String.class); return result; }
轮询的算法策略:
eureka的客户端已经一如了ribbon
自己配置均衡算法: /** * 测试自己写的轮询算法 * @return */ public interface LoadBalancer { ServiceInstance instances(List<ServiceInstance> serviceInstances); }
/** * 测试自己写的轮询算法 * @return */ @Component public class MyLB implements LoadBalancer { private AtomicInteger nextServerCyclicCounter=new AtomicInteger(0); public final int cas(){ int current; int next; do{ current=this.nextServerCyclicCounter.get(); next=current>=2147483647?0:current+1; }while (!this.nextServerCyclicCounter.compareAndSet(current,next)); System.out.println("****next:"+next); return next; } @Override public ServiceInstance instances(List<ServiceInstance> serviceInstances) { int index=cas() % serviceInstances.size(); return serviceInstances.get(index); } } @Resource private DiscoveryClient discoveryClient; @Resource
private LoadBalancer loadBalancer;
/**
* 测试自己写的轮询算法
* @return
*/
public interface LoadBalancer {
ServiceInstance instances(List<ServiceInstance> serviceInstances);
}
/** * 测试自己写的轮询算法 * @return */ @GetMapping("/consumer/lb") public String lb() { List<ServiceInstance> instances=discoveryClient.getInstances("CLOUD-PAYMENT-SERVER"); if(instances==null||instances.size()<=0){ return null; } ServiceInstance serviceInstance=loadBalancer.instances(instances); URI uri=serviceInstance.getUri(); return restTemplate.getForObject(uri+"/payment/payment/lb",String.class); } { Ribbon里面的负载均衡算法是基于客户端的, nginx的负载均衡是基于服务端的 接口第几次请求数%服务器集群总数量=实际调用服务器下标,每次重启后rest接口计数器从1开始 List<ServiceInstance>instances=discoveryClient.getInstance("cloud-order-server") List【0】instances=127.0.0.1:8002 List【1】instances=127.0.0.1:8001 8001 8002两台集群 ,集群数为2,按照轮询法则原理: 请求数为1时:1%2=1对应的下标位置为1,获得服务器地址为127.0.0.1:8001 请求数为2时:2%2=1对应的下标位置为0,获得服务器地址为127.0.0.1:8002 请求数为3时:3%2=1对应的下标位置为1,获得服务器地址为127.0.0.1:8001 请求数为4时:4%2=1对应的下标位置为0,获得服务器地址为127.0.0.1:8002 请求数为5时:5%2=1对应的下标位置为1,获得服务器地址为127.0.0.1:8001 }
调用某个服务随机算法 @RibbonClient(name="CLOUD-PAYMENT-SERVER",configuration = MySelfRule.class)//轮询配置 @Configurable public class MySelfRule { @Bean public IRule myRule(){ return new RandomRule();//随机 } }