负载均衡组件Spring Cloud Ribbon(一)-服务消费者接入ribbon(通过Eureka整合)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenzhen_zsw/article/details/89443315

目录

 

负载均衡组件Spring Cloud Ribbon(一)-服务消费者接入ribbon(通过Eureka整合)

Ribbon介绍

服务消费者接入ribbon(通过Eureka整合)

为消费者整合Ribbon

Controller

测试

服务消费者接入Ribbon(脱离Eureka)


 

负载均衡组件Spring Cloud Ribbon(一)-服务消费者接入ribbon(通过Eureka整合)

Ribbon介绍

服务消费者接入ribbon(通过Eureka整合)

为消费者整合Ribbon

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

注:由于我们的项目配合Eureka使用,spring-cloud-starter-eureka包含了spring-cloud-starter-ribbon,所以无需再次引入依赖。

在上文中我们通过RestTemplate来实现请求,那我们在RestTemplate上面添加@LoadBalanced注解

/**
 * ConsumerMovieApplication class
 */
@EnableDiscoveryClient
@SpringBootApplication
public class ConsumerMovieApplication {

    //添加LoadBalanced注解来整合Ribbon使其具有负载均衡的能力
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ConsumerMovieApplication.class,args);
    }
}

Controller

package com.TransientBa.cloud.controller;

import com.TransientBa.cloud.pojo.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.List;

/**
 * MovieController class
 */
@RestController
public class MovieController {

    private static Logger LOGGER = LoggerFactory.getLogger(MovieController.class);

    //使用restTemplate请求User服务
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DiscoveryClient discoveryClient;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    //读取配置文件Url路径  
    @Value("${user.userServiceUrl}")
    private String userServiceUrl;


    @GetMapping(value = "/user/{id}")
    public User findById(@PathVariable Long id){
   		 //下面这个userServiceUrl 为配置文件中读取的http://microservice-provider-user/地址  该地址为服务提供者的虚拟主机名 配合Eureka使用会自动将其映射成微服务的网络地址  即前面提到的8001 8000
        return this.restTemplate.getForObject(userServiceUrl + id,User.class);

    }

    /***
     * 查询microservice-provider-user服务的信息并返回
     * @return microservice-provider-user服务的信息
     *
     * 使用DiscoveryClient.getInstances(serviceId),可查询指定微服务在Eureka上的实例列表
     */
    @GetMapping(value = "/user-instance", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<ServiceInstance> showInfo(){
        return this.discoveryClient.getInstances("microservice-provider-user");
    }


    /**=
     * 打印当前选择的是哪个节点
     */
    @GetMapping("/log-instance")
    public void logUserInstance(){
        ServiceInstance serviceInstance = this.loadBalancerClient.choose("microservice-provider-user");
        MovieController.LOGGER.info("{}:{}:{}",serviceInstance.getServiceId(),serviceInstance.getHost(),serviceInstance.getPort());
    }
}

    @GetMapping(value = "/user/{id}")
    public User findById(@PathVariable Long id){
        // 下面这个userServiceUrl 为配置文件中读取的http://microservice-provider-user/地址
        // 该地址为服务提供者的虚拟主机名 配合Eureka使用会自动将其映射成微服务的网络地址 
        // 即前面提到的8001 8000
        return this.restTemplate.getForObject(userServiceUrl + id,User.class);
    }

注:此处有一点需要注意,restTemplate.getForObject和loadBalancerClient.choose不能同时在一个方法中使用,因为restTemplate上的@LoadBalanced注解使其在这里成为了一个Ribbon客户端,本身已经包含了choose的行为,放在一起会产生冲突。
 

测试

    可以看到Server分别发现了两个叫MICROSERVICE-PROVIDER-USER的服务提供者,一个叫MICROSERVIECE-CONSUMER-MOVIE的消费者,下面我们通过多次请求/user/{id}接口来观察下两个服务提供者打印的日志。

多次访问http://localhost:8010/user/1

接口多次请求后,两个微服务提供者的控制台都输出了查询语句
 

==============================

QQ群:143522604

群里有相关资源

欢迎和大家一起学习、交流、提升!

==============================

猜你喜欢

转载自blog.csdn.net/shenzhen_zsw/article/details/89443315