SpringCloud中如何使用Ribbon和RestTemplate实现服务调用和负载平衡

猿友 2021-08-04 11:28:59 浏览数 (2077)
反馈

SpringCloud 是目前微服务架构领域的翘楚,备受开发者和企业的青睐。下面,我将介绍 SpringCloud 中是如何使用 Ribbon 工具框架和 RestTemplate 模板类来实现服务调用和负载平衡。

文件目录结构

202148100124156

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

写pom

<dependencies>
        <!--springboot 2.2.2-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--Spring cloud Hoxton.SR1-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <!--Spring cloud alibaba 2.1.0.RELEASE-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--Eureka-Client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

因为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<CommonResult> resultResponseEntit = restTemplate.getForEntity(PAYMENT_URL+"/book/getAllBooks",CommonResult.class);
        if (resultResponseEntit.getStatusCode().is2xxSuccessful()){
            log.info(resultResponseEntit.getStatusCode()+"	"+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<ServiceInstance> 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<ServiceInstance> 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<ServiceInstance> 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<ServiceInstance> 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算法并使用完成

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


0 人点赞