springcloud中Ribbon和RestTemplate实现服务调用与负载均衡

2025-05-29 0 45

文件目录结构

springcloud中Ribbon和RestTemplate实现服务调用与负载均衡

文件目录结构很重要,特别注意的是rule文件要放在主启动类上一级位置,才能够扫描。

写pom

  1. <dependencies>
  2. <!–springboot 2.2.2–>
  3. <dependency>
  4. <groupId>org.springframework.boot</groupId>
  5. <artifactId>spring-boot-starter-web</artifactId>
  6. </dependency>
  7. <!–Spring cloud Hoxton.SR1–>
  8. <dependency>
  9. <groupId>org.springframework.boot</groupId>
  10. <artifactId>spring-boot-starter-actuator</artifactId>
  11. </dependency>
  12. <!–Spring cloud alibaba 2.1.0.RELEASE–>
  13. <dependency>
  14. <groupId>org.projectlombok</groupId>
  15. <artifactId>lombok</artifactId>
  16. <optional>true</optional>
  17. </dependency>
  18. <dependency>
  19. <groupId>org.springframework.boot</groupId>
  20. <artifactId>spring-boot-starter-test</artifactId>
  21. <scope>test</scope>
  22. </dependency>
  23. <!–Eureka-Client–>
  24. <dependency>
  25. <groupId>org.springframework.cloud</groupId>
  26. <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
  27. </dependency>

因为eureka的依赖已经整合了ribbon的依赖,所以不用额外引入新的东西。

改yml

  1. server:
  2. port: 80
  3. spring:
  4. application:
  5. name: cloudbookconsumer
  6. eureka:
  7. client:
  8. registerwitheureka: false
  9. fetchregistry: true
  10. serviceurl:
  11. defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

主启动

  1. @SpringBootApplication
  2. @EnableEurekaClient
  3. @RibbonClient(name = "CLOUD-BOOK-SERVICE", configuration = LoadBalanceRule.class) //更换轮询算法
  4. public class RestTemplateMain80 {
  5. public static void main(String[] args) {
  6. SpringApplication.run(RestTemplateMain80.class,args);
  7. }
  8. }

业务逻辑

rules层

在图示文件目录下新建LoadBalanceRule.class,用于更换负载均衡算法。

  1. @Configuration
  2. public class LoadBalanceRule {
  3. @Bean
  4. public IRule iRule() {
  5. // 定义为随机
  6. return new RandomRule();
  7. }
  8. }

config层

开启restTemplate负载均衡
在config文件夹下创建LoadBalanceConfig.class

  1. @Configuration
  2. public class LoadBalanceConfig {
  3. @Bean
  4. @LoadBalanced //开启负载均衡
  5. public RestTemplate getReatTemplate(){
  6. return new RestTemplate();
  7. }
  8. }

controller层

新建BookController.class
写业务代码

  1. @RestController
  2. @Slf4j
  3. public class BookController {
  4. @Resource
  5. private RestTemplate restTemplate;
  6. public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
  7. @GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
  8. public CommonResult getAllBooks(){
  9. return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
  10. }
  11. @GetMapping("restTemplate/book/getAllBooks2") //需要知道更多数据时,使用getForEntity方法
  12. public CommonResult getAllBooks2(){
  13. ResponseEntity<CommonResult> resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
  14. if (resultResponseEntit.getStatusCode().is2xxSuccessful()){
  15. log.info(resultResponseEntit.getStatusCode()+"\\t"+resultResponseEntit.getHeaders());
  16. return resultResponseEntit.getBody();
  17. }else {
  18. return new CommonResult<>(444,"操作失败");
  19. }
  20. }
  21. @GetMapping(value = "restTemplate/book/index")
  22. public String index() {
  23. return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class);
  24. }
  25. }

使用restTemplate+Ribboin实现服务调用负载均衡完成。

手写Ribbon负载均衡算法 lb层

1.新建LoadBalancer接口,添加代码

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

2.新建实现类MyLB

  1. @Component
  2. public class MyLB implements LoadBalancer {
  3. private AtomicInteger atomicInteger = new AtomicInteger(0);
  4. //求第几次访问 自旋锁思想
  5. public final int getAndIncrement(){
  6. int current;
  7. int next;
  8. do {
  9. current = this.atomicInteger.get();
  10. next = current >=2147483647 ? 0 : current+1;
  11. }while(!this.atomicInteger.compareAndSet(current,next));
  12. System.out.println("***第几次访问next->"+next);
  13. return next;
  14. }
  15. //负载均衡算法,实现roundRobin算法
  16. @Override
  17. public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
  18. int index = getAndIncrement() % serviceInstances.size();
  19. return serviceInstances.get(index);
  20. }
  21. }

修改BookController

  1. @RestController
  2. @Slf4j
  3. public class BookController {
  4. @Resource
  5. private RestTemplate restTemplate;
  6. @Resource
  7. private LoadBalancer loadBalancer;
  8. @Resource
  9. private DiscoveryClient discoveryClient;
  10. public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
  11. @GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
  12. public CommonResult getAllBooks(){
  13. List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
  14. if (instances == null || instances.size() <= 0){
  15. return null;
  16. }
  17. ServiceInstance serviceInstance = loadBalancer.instances(instances);
  18. URI uri = serviceInstance.getUri();
  19. return restTemplate.getForObject(uri+"/book/getAllBooks",CommonResult.class);
  20. }
  21. @GetMapping(value = "restTemplate/book/index")
  22. public String index() {
  23. List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
  24. if (instances == null || instances.size() <= 0){
  25. return null;
  26. }
  27. ServiceInstance serviceInstance = loadBalancer.instances(instances);
  28. URI uri = serviceInstance.getUri();
  29. return restTemplate.getForObject(uri+"/book/index",String.class);
  30. }
  31. }

修改文件注解

@RibbonClient(name = “CLOUD-BOOK-SERVICE”, configuration = LoadBalanceRule.class)

@LoadBalanced

手写Ribbon算法并使用完成

以上就是RibbonRestTemplate实现服务调用负载均衡的详细内容,更多关于RibbonRestTemplate服务与负载的资料请关注快网idc其它相关文章!

原文链接:https://blog.csdn.net/super1223/article/details/115384982

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 springcloud中Ribbon和RestTemplate实现服务调用与负载均衡 https://www.kuaiidc.com/107428.html

相关文章

发表评论
暂无评论