服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - springcloud中Ribbon和RestTemplate实现服务调用与负载均衡

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

2021-09-02 12:45何羡仙 Java教程

这篇文章主要介绍了Ribbon和RestTemplate实现服务调用与负载均衡,想了解负载均衡的同学可以参考下

文件目录结构

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: cloud-book-consumer
  6. eureka:
  7. client:
  8. register-with-eureka: false
  9. fetch-registry: true
  10. service-url:
  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.  
  7. public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";
  8.  
  9. @GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
  10. public CommonResult getAllBooks(){
  11. return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
  12. }
  13.  
  14. @GetMapping("restTemplate/book/getAllBooks2") //需要知道更多数据时,使用getForEntity方法
  15. public CommonResult getAllBooks2(){
  16. ResponseEntity<CommonResult> resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
  17. if (resultResponseEntit.getStatusCode().is2xxSuccessful()){
  18. log.info(resultResponseEntit.getStatusCode()+"\t"+resultResponseEntit.getHeaders());
  19. return resultResponseEntit.getBody();
  20. }else {
  21. return new CommonResult<>(444,"操作失败");
  22. }
  23. }
  24. @GetMapping(value = "restTemplate/book/index")
  25. public String index() {
  26. return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class);
  27. }
  28. }

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

修改BookController

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

修改文件注解

  • 删去主启动类的更换负载均衡算法注解

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

  • 删去LoadBalanceConfig中开启负载均衡算法注解

@LoadBalanced

手写Ribbon算法并使用完成

以上就是Ribbon和RestTemplate实现服务调用与负载均衡的详细内容,更多关于Ribbon和RestTemplate服务与负载的资料请关注服务器之家其它相关文章!

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

延伸 · 阅读

精彩推荐