当前位置: 首页 > news >正文

SpringCloud-负载均衡Ribbon

  一、配置使用

       1、添加依赖(该依赖包含在eureka-client依赖中

<dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-ribbon</artifactId></dependency>

        2、在RestTemplate上添加@LoadBalanced注解

@Configuration
public class ApplicationContextConfig {@Bean@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();}
}
  二、IRule替换负载策略

        以随机为例

        1、添加配置类(注意不要放到@ComponentScan所能扫描到的包下

@Configuration
public class MyStyleRule {@Beanpublic IRule myRule(){/*** 定义为随机*/return new RandomRule();}
}

       2、在启动类上添加注解

              @RibbonClient(name = "CLOUD-PAYMENT-SERVICE",configuration = MyStyleRule.class)

             name:为服务注册名称

             configuration:为策略类

      3、自定义实现轮询策略

          声明接口

public interface LoadBalancer {ServiceInstance instances(List<ServiceInstance> serviceInstances);
}

         实现接口

@Component
public class MyLb implements LoadBalancer
{private AtomicInteger atomicInteger = new AtomicInteger(0);public final int getAndIncremant(){int current;int next;do{current = this.atomicInteger.get();//Integer.MAX_VALUE=2147483647next = current >= Integer.MAX_VALUE ? 0 : current +1 ;}while(!this.atomicInteger.compareAndSet(current,next));return next;};@Overridepublic ServiceInstance instances(List<ServiceInstance> serviceInstances) {int index = getAndIncremant() % serviceInstances.size();return serviceInstances.get(index);}
}

       测试代码

    @Resourceprivate RestTemplate restTemplate;@Resourceprivate LoadBalancer loadBalancer;@Resourceprivate DiscoveryClient discoveryClient;@GetMapping("/consumer/payment/lb")public String getPaymentLB(){List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");if(instances == null || instances.size() <= 0){return null;}else{ServiceInstance serviceInstance = loadBalancer.instances(instances);URI uri = serviceInstance.getUri();return restTemplate.getForObject(uri+"/payment/lb",String.class);}}
http://www.lryc.cn/news/8371.html

相关文章:

  • Linux入门篇(二)
  • 第四部分:特殊用途的句子——第三章:虚拟
  • Java中如何获取泛型类型信息
  • 【云原生】centos7搭建安装k8s集群 v1.25版本详细教程实战
  • c语言指针
  • 5.33 综合案例2.0 -ESP32拍照上传阿里云OSS
  • java无重复字符的最长子串
  • 测试用例设计工作中的应用
  • leetcode 困难 —— 数字 1 的个数(简单逻辑题)
  • 关于JSON
  • Apifox-接口调用、自动化测试工具
  • Vue一个项目兼容每个省份的个性化需求
  • npm install报错 npm ERR! 的解决办法
  • echarts修改饼图,环形图的圆环宽度,大小
  • 小白系列Vite-Vue3-TypeScript:010-封装svg
  • 卷严重、难度高、激励少,如何适应空投市场新变化
  • 基于Java与JSP的文件上传和下载
  • Gromacs中的g_mmpbsa计算带电底物与蛋白的结合能不准确
  • 【mmrotate】旋转目标检测之训练DOTA数据集
  • 图基本概念
  • 机器学习基础
  • FreeRTOS-Tickless低功耗模式 | FreeRTOS十四
  • 实现了统一消息中心的微服务基础框架 JVS,快点赞收藏
  • VMware 安装 OpenWrt 旁路由并配置 PassWall
  • R语言GD包地理探测器分析时报错、得不到结果等情况的解决方案
  • 嵌入式开发:你需要知道的5种简单
  • MVC与MVVM
  • Cortex-M0异常和中断
  • 数据库(6)--存储过程
  • c++ 指针、引用和常量