当前位置:  开发笔记 > 前端 > 正文

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

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

文件目录结构

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

写pom


        
        
            org.springframework.boot
            spring-boot-starter-web
        
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        

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

改yml

server:
  port: 80
spring:
  application:
    name: cloud-book-consumer
eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka

主启动

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

业务逻辑

rules层

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

@Configuration
public class LoadBalanceRule {
    @Bean
    public IRule iRule() {
        // 定义为随机
        return new RandomRule();
    }
}

config层

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

@Configuration
public class LoadBalanceConfig {
    @Bean
    @LoadBalanced            //开启负载均衡
    public RestTemplate getReatTemplate(){
        return new RestTemplate();
    }
}

controller层

新建BookController.class
写业务代码

@RestController
@Slf4j
public class BookController {
    @Resource
    private RestTemplate restTemplate;

    public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";

    @GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
    public CommonResult getAllBooks(){
        return restTemplate.getForObject(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
    }

    @GetMapping("restTemplate/book/getAllBooks2")    //需要知道更多数据时,使用getForEntity方法
    public CommonResult getAllBooks2(){
        ResponseEntity resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
        if (resultResponseEntit.getStatusCode().is2xxSuccessful()){
            log.info(resultResponseEntit.getStatusCode()+"\t"+resultResponseEntit.getHeaders());
            return resultResponseEntit.getBody();
        }else {
            return new CommonResult<>(444,"操作失败");
        }
    }
    @GetMapping(value = "restTemplate/book/index")
    public String index() {
        return restTemplate.getForObject(PAYMENT_URL+"/book/index",String.class);
    }
}

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

手写Ribbon负载均衡算法 lb层

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

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

2.新建实现类MyLB

@Component
public class MyLB implements LoadBalancer {

    private AtomicInteger atomicInteger = new AtomicInteger(0);
    //求第几次访问  自旋锁思想
    public final int getAndIncrement(){
        int current;
        int next;
        do {
            current = this.atomicInteger.get();
            next = current >=2147483647 ? 0 : current+1;
        }while(!this.atomicInteger.compareAndSet(current,next));
        System.out.println("***第几次访问next->"+next);
        return next;
    }

    //负载均衡算法,实现roundRobin算法
    @Override
    public ServiceInstance instances(List serviceInstances) {

        int index = getAndIncrement() % serviceInstances.size();

        return serviceInstances.get(index);
    }
}

修改BookController

@RestController
@Slf4j
public class BookController {
    @Resource
    private RestTemplate restTemplate;

    @Resource
    private LoadBalancer loadBalancer;

    @Resource
    private DiscoveryClient discoveryClient;

    public static final String PAYMENT_URL = "http://CLOUD-BOOK-SERVICE";

    @GetMapping(value = "restTemplate/book/getAllBooks")//只要json数据时
    public CommonResult getAllBooks(){
        List instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
        if (instances == null || instances.size() <= 0){
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/book/getAllBooks",CommonResult.class);
    }

    @GetMapping(value = "restTemplate/book/index")
    public String index() {
        List instances = discoveryClient.getInstances("CLOUD-BOOK-SERVICE");
        if (instances == null || instances.size() <= 0){
            return null;
        }
        ServiceInstance serviceInstance = loadBalancer.instances(instances);
        URI uri = serviceInstance.getUri();
        return restTemplate.getForObject(uri+"/book/index",String.class);
    }
}

修改文件注解

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

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

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

@LoadBalanced

手写Ribbon算法并使用完成

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

推荐阅读
手机用户2402851335
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有