四:服务消费(LoadBalancerClient、Ribbon、Feign)

通过上一篇《三:服务的注册与发现(Eureka》,我们已经成功地将服务提供者:provider-test注册到了Eureka服务注册中心上了,那么接下来我们要学习的就是:如何去消费服务提供者的接口?

4.1使用LoadBalancerClient

在Spring Cloud Commons中提供了大量的与服务治理相关的抽象接口,包括DiscoveryClient、LoadBalancerClient等。从LoadBalancerClient接口的命名中,可以看出这是一个负载均衡客户端的抽象定义,下面笔者将使用Spring Cloud提供的负载均衡器客户端接口来实现服务的消费。

首先,将利用上一篇中构建的eureka-server作为服务注册中心、provider-test作为服务提供者为基础。

  • 创建一个叫voyer-consumer-test的Spring Boot项目,引入相关maven包。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.voyer</groupId>
    <artifactId>voyer-consumer-test</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>voyer-consumer-test</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <spring-cloud.version>Finchley.M9</spring-cloud.version>
    </properties>


    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>


</project>
  • 然后配置application.yml,指定服务注册中心地址、端口号以及名称
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8764
spring:
  application:
    name: consumer-test
  • 在默认的启动程序中注入RestTemplate
@SpringBootApplication
public class VoyerConsumerTestApplication {

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

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  • 创建com.voyer.web包路径,创建ConsumerController,并注入 LoadBalancerClientRestTemplate,并在/hi接口的实现中,先通过loadBalancerClientchoose函数来负载均衡的选出一个provider-test的服务实例,这个服务实例的基本信息存储在ServiceInstance中,然后通过这些对象中的信息拼接出访问/hi接口的详细地址,最后再利用RestTemplate对象实现对服务提供者接口的调用:
@RestController
public class ConsumerController {
    @Autowired
    LoadBalancerClient loadBalancerClient;
    @Autowired
    RestTemplate restTemplate;

    @RequestMapping("/hi")
    public String hello(){
        ServiceInstance serviceInstance = loadBalancerClient.choose("provider-test");
        String url = "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/hi";
        System.out.println(url);
        return restTemplate.getForObject(url, String.class);
    }
}

访问http://localhost::8764/hi ,会发现每次访问的返回的信息会循环输出hello world! I am from 8763hello world! I am from 8762

4.2使用Ribbon

Spring Cloud Ribbon是基于Netflix Ribbon实现的一套客户端负载均衡的工具。它是一个基于HTTP和TCP的客户端负载均衡器。它可以通过在客户端中配置ribbonServerList来设置服务端列表去轮询访问以达到均衡负载的作用。
每个load balancer都是组件的一部分,这些组件协同工作,Spring Cloud通过使用RibbonClientConfiguration为每个指定的客户端创建一个新的套装,这包括ILoadBalancer、RestClient和ServerListFilter。

  • 创建一个叫voyer-consumer-ribbon的Spring Boot项目,(操作顺序同上)引入相关maven包
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
  • 修改默认启动类。增加为@EnableEurekaClient注解(此处为什么不用@EnableDiscoveryClient,读者可以百度一下这两者的区别),RestTemplate增加@LoadBalanced注解:
@SpringBootApplication
@EnableEurekaClient
public class VoyerConsumerRibbonApplication {

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

    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}
  • 修改配置文件application.yml
eureka:
  client:
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8765
spring:
  application:
    name: consumer-ribbon
  • 修改ConsumerController:
@RestController
public class ConsumerController {
    @Autowired
    RestTemplate restTemplate;
    @RequestMapping("/hi")
    public String hello(){
        return restTemplate.getForObject("http://PROVIDER-TEST/hi", String.class);
    }
}

启动程序,然后访问http://localhost:8765,会发现

hello world! I am from 8762
hello world! I am from 8763

这两个循环出现。到此ribbon消费者成功。

4.3使用Feign

Feign是一个声明性的web服务客户端,它使编写web服务客户机变得更容易。使用Feign创建接口并对其进行注释。它有可插入的注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插入式的编码器和解码器。Spring Cloud增加了对Spring MVC注释的支持,并支持在Spring Web中使用默认的HttpMessageConverters。Spring Cloud集成了Ribbon和Eureka,在使用Feign时提供负载平衡的http客户端。(来自有道翻译)
总结两点:1、Feign采用的是接口加注解;2、Feign 整合了ribbon

  • 创建一个叫voyer-consumer-feign的Spring Boot项目,(操作顺序同上)引入相关maven包
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
  • 配置文件:registerWithEureka: false自身是消费者,不注册为服务提供者。
eureka:
  client:
    registerWithEureka: false
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8766
spring:
  application:
    name: consumer-feign
  • 默认启动类增加@EnableDiscoveryClient@EnableFeignClients注解:
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class VoyerConsumerFeignApplication {

    public static void main(String[] args) {
        SpringApplication.run(VoyerConsumerFeignApplication.class, args);
    }
}
  • 创建service包路径,然后新建一个ConsumerService的接口,通过@ FeignClient(“服务名”),来指定调用哪个服务:
@FeignClient(value = "provider-test")
public interface ConsumerService {
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    String hiFromProvider();
}
  • 创建com.voyer.web包路径,创建ConsumerController:
@RestController
public class ConsumerController {
    @Autowired
    ConsumerService consumerService;
    @RequestMapping(value = "/hi",method = RequestMethod.GET)
    public String hi(){
        return consumerService.hiFromProvider();
    }
}

启动程序,然后访问http://localhost:8766,会发现

hello world! I am from 8762
hello world! I am from 8763

这两个循环出现。到此feign消费者成功。

推荐阅读更多精彩内容