• Ribbon负载均衡算法


    负载均衡算法:rest接口第几次请求数 % 服务器集群总数量 = 实际调用服务器位置下标  ,每次服务重启动后rest接口计数从1开始。
     
    List instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
     
    如:   List [0] instances = 127.0.0.1:8002
       List [1] instances = 127.0.0.1:8001
     
    8001+ 8002 组合成为集群,它们共计2台机器,集群总数为2, 按照轮询算法原理:
     
    当总请求数为1时: 1 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
    当总请求数位2时: 2 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
    当总请求数位3时: 3 % 2 =1 对应下标位置为1 ,则获得服务地址为127.0.0.1:8001
    当总请求数位4时: 4 % 2 =0 对应下标位置为0 ,则获得服务地址为127.0.0.1:8002
    如此类推......

     

    写一个本地负载均衡器 

    设现在有俩个服务端口8001 8002幼由80端口调动

    其中8001 8002 的controller中 

    1. @GetMapping(value = "/payment/lb")
    2. public String getPaymentLB()
    3. {
    4. return serverPort;
    5. }

    80 的一个接口为:

    1. public interface LoadBalancer
    2. {
    3. ServiceInstance instances(List serviceInstances);
    4. }

     实现类

    1. @Component
    2. public class MyLB implements LoadBalancer
    3. {
    4. private AtomicInteger atomicInteger = new AtomicInteger(0);
    5. public final int getAndIncrement()
    6. {
    7. int current;
    8. int next;
    9. do
    10. {
    11. current = this.atomicInteger.get();
    12. next = current >= 2147483647 ? 0 : current + 1;
    13. } while(!this.atomicInteger.compareAndSet(current, next));
    14. System.out.println("*****next: "+next);
    15. return next;
    16. }
    17. @Override
    18. public ServiceInstance instances(List serviceInstances)
    19. {
    20. int index = getAndIncrement() % serviceInstances.size();
    21. return serviceInstances.get(index);
    22. }
    23. }

    调用 方法

    1. @Resource
    2. private RestTemplate restTemplate;
    3. //可以获取注册中心上的服务列表
    4. @Resource
    5. private DiscoveryClient discoveryClient;
    6. @Resource
    7. private LoadBalancer loadBalancer;
    8. @GetMapping("/consumer/payment/lb")
    9. public String getPaymentLB()
    10. {
    11. List instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
    12. if(instances == null || instances.size()<=0) {
    13. return null;
    14. }
    15. ServiceInstance serviceInstance = loadBalancer.instances(instances);
    16. URI uri = serviceInstance.getUri();
    17. return restTemplate.getForObject(uri+"/payment/lb",String.class);
    18. }

    ApplicationContextBean去掉注解@LoadBalanced 

  • 相关阅读:
    SpringBoot启动流程分析之创建SpringApplication对象(一)
    Day88.七牛云: 房源图片、用户头像上传
    Django入门2
    C1W1.LAB.Preprocessing+Word frequencies+Logistic_regression_model
    【JavaWeb】01_Tomcat、Servlet、Thymeleaf
    Vision Transformer这两年
    NC16466 [NOIP2015]信息传递 (带权并查集)
    JMeter处理接口签名sign
    如何解决基因行业海量数据传输难题?镭速传输给出答案
    直击第一届中国测绘地理信息大会,华测导航强势出圈!
  • 原文地址:https://blog.csdn.net/m0_62436868/article/details/126282843