Spring Cloud Finchley.SR1 的学习与应用 6 - 服务消费

Ribbon

服务提供者

服务提供者已经在《Spring Cloud Finchley.SR1 的学习与应用 4 - 服务注册》一文中作了明确说明,这里不在赘述了。java

服务消费者

建立服务消费者根据使用 API 的不一样,大体分为三种方式。虽然你们在实际使用中用的应该都是 Feign,可是这里仍是把这三种都介绍一下web

建立业务系统B,与业务系统A相似spring

  • 建立modules-woqu,继承parent-woqu,用于管理业务系统项目
<?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">
    <parent>
        <artifactId>modules-woqu</artifactId>
        <groupId>com.orrin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>businessb-woqu</artifactId>
    <packaging>pom</packaging>
    <modules>
        <module>client-businessb-woqu</module>
        <module>server-businessb-woqu</module>
    </modules>


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

    </dependencies>
</project>
  • 建立businessa-woqu业务系统B

包含业务系统客户端client-businessb-woqu和服务端server-businessb-woquapache

<?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">
    <parent>
        <artifactId>businessb-woqu</artifactId>
        <groupId>com.orrin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>client-businessb-woqu</artifactId>


    <dependencies>
        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>model-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>


        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>core-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>
</project>
  • 业务系统B服务端

下面咱们服务消费的客户端,并向服务注册中心注册本身。 假设咱们有一个提供长方体表面积计算功能的微服务模块,咱们实现一个RESTful API,经过传入三个参数length、width、heigh,最后返回长方体表面积。json

建立client-businessa-woquapp

<?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">
    <parent>
        <artifactId>businessb-woqu</artifactId>
        <groupId>com.orrin</groupId>
        <version>0.0.1-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>server-businessb-woqu</artifactId>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-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-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.jolokia</groupId>
            <artifactId>jolokia-core</artifactId>
        </dependency>

        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>client-businessa-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
        <dependency>
            <groupId>com.orrin</groupId>
            <artifactId>client-businessb-woqu</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>

    </dependencies>

</project>

配置文件负载均衡

spring:
  application:
    name: business-b-woqu
  cloud:
    consul:
      host: woqu.consul
      port: 8500
      discovery:
        instance-id: ${spring.application.name}
        instance-group: ${spring.application.name}
        register: true

server:
  port: 9002
  
feign:
  hystrix:
    enabled: true

logging:
  level:
    root: info
    com.woqu: debug
    
hystrix.command.default.execution.isolation.thread.timeoutInMilliseconds: 60000
ribbon:
  ConnectTimeout: 10000
  ReadTimeout: 60000

启动类:maven

package com.woqu.business.b.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

/**
 * @author orrin
 */

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.woqu")
@ComponentScan(value = "com.woqu")
public class BusinessBApp {
    public static void main(String[] args) {
        SpringApplication.run(BusinessBApp.class, args);
    }
}

使用 LoadBalancerClient

初始化RestTemplate,用来发起 REST 请求。函数

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

建立一个接口用来消费 producer(business-a-woqu) 提供的接口:spring-boot

@RestController
public class ConsumeController {

    @Autowired
    private LoadBalancerClient client;

    @Autowired
    private RestTemplate restTemplate;
    
    private Integer multiply(int x, int y) {
        return x * y;
    }
    
    @GetMapping("/area/2")
    public Integer cuboidArea2(@RequestParam("length") int length, @RequestParam("width") int width, @RequestParam("heigh") int heigh) {
        LOGGER.info("length = {}, width = {}, heigh = {}");
        return  this.multiply(2, this.add2(this.add2(this.multiply(length, width), this.multiply(width, heigh)), this.multiply(length, heigh)));
    }

    /**
     * 使用 LoadBalancerClient 消费business-a-woqu中的方法
     */
    private Integer add2(int x, int y) {
        ServiceInstance instance = client.choose("business-a-woqu");
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/add?x=" + x + "&y=" + y;
        return restTemplate.getForObject(url, Integer.class);
    }
}

能够看到这里,咱们注入了LoadBalancerClient和RestTemplate,并在hello方法中,先经过loadBalancerClient的choose方法来负载均衡的选出一个business-a-woqu的服务实例,这个服务实例的基本信息存储在ServiceInstance中,而后经过这些对象中的信息拼接出访问服务调用者的/add接口的详细地址,最后再利用RestTemplate对象实现对服务提供者接口的调用。

验证是否调用成功

GET http://127.0.0.1:9002/area/2?length=1&width=2&heigh=3

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 19 Nov 2018 06:29:45 GMT

22

Response code: 200; Time: 1576ms; Content length: 2 bytes

Spring Cloud Ribbon

Ribbon是一个基于 HTTP 和 TCP 的客户端负载均衡器。它能够经过在客户端中配置 ribbonServerList 来设置服务端列表去轮询访问以达到均衡负载的做用。

为RestTemplate添加@LoadBalanced注解

@LoadBalanced
@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

修改 controller,去掉LoadBalancerClient,并修改相应的方法,直接用 RestTemplate发起请求

@RestController
public class ConsumeController {
    private Integer multiply(int x, int y) {
        return x * y;
    }
    
    /**
     * 使用 Ribbon 消费business-a-woqu中的方法
     */
    private Integer add3(int x, int y) {
        ServiceInstance instance = client.choose("business-a-woqu");
        String url = "http://business-a-woqu/add?x=" + x + "&y=" + y;
        return restTemplate.getForObject(url, Integer.class);
    }

    @GetMapping("/area/3")
    public Integer cuboidArea3(@RequestParam("length") int length, @RequestParam("width") int width, @RequestParam("heigh") int heigh) {
        LOGGER.info("length = {}, width = {}, heigh = {}");
        return  this.multiply(2, this.add3(this.add3(this.multiply(length, width), this.multiply(width, heigh)), this.multiply(length, heigh)));
    }
}

这里直接用服务名eureka-producer取代了以前的具体的host:port。那么这样的请求为何能够调用成功呢?由于 Spring Cloud Ribbon 有一个拦截器,它可以在这里进行实际调用的时候,自动的去选取服务实例,并将这里的服务名替换成实际要请求的 IP 地址和端口,从而完成服务接口的调用。

验证是否调用成功

GET http://192.168.2.102:9002/area/3?length=2&width=2&heigh=3

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 19 Nov 2018 06:47:17 GMT

32

Response code: 200; Time: 67ms; Content length: 2 bytes

使用 Spring Cloud Feign

在实际工做中,咱们基本上都是使用 Feign 来完成调用的。咱们经过一个例子来展示 Feign 如何方便的声明对 business-a-woqu 服务的定义和调用。

  • POM 包配置
    在 pom.xml 中添加以下配置:
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  • 启动类
    @EnableFeignClients(basePackages = "com.woqu")
/**
 * @author orrin
 */

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "com.woqu")
@ComponentScan(value = "com.woqu")
public class BusinessBApp {
    public static void main(String[] args) {
        SpringApplication.run(BusinessBApp.class, args);
    }
}
  • Feign 调用实现
    建立一个 Feign 的客户端接口定义。使用@FeignClient注解来指定这个接口所要调用的服务名称,接口中定义的各个函数使用 Spring MVC 的注解就能够来绑定服务提供方的 REST 接口,好比下面就是绑定 business-a-woqu 服务的/add接口的例子:
/**
 * @author orrin on 2018/7/4
 */
@FeignClient(serviceId = "business-a-woqu")
public interface Addition {

    @GetMapping("/add")
    public Integer add(@RequestParam("x") int x, @RequestParam("y") int y);
}

此类中的方法和远程服务中 Contoller 中的方法名和参数需保持一致。

  • Controller
    修改 Controller,将 HelloRemote 注入到 controller 层,像普通方法同样去调用便可
@RestController
public class ConsumeController {
    @Autowired
    private Addition a;
    
    
    private Integer multiply(int x, int y) {
        return x * y;
    }
    
    @GetMapping("/area")
    public Integer cuboidArea(@RequestParam("length") int length, @RequestParam("width") int width, @RequestParam("heigh") int heigh) {
        LOGGER.info("length = {}, width = {}, heigh = {}");
        return  this.multiply(2, a.add(a.add(this.multiply(length, width), this.multiply(width, heigh)), this.multiply(length, heigh)));
    }
}

经过 Spring Cloud Feign 来实现服务调用的方式很是简单,经过@FeignClient定义的接口来统一的声明咱们须要依赖的微服务接口。而在具体使用的时候就跟调用本地方法一点的进行调用便可。因为 Feign 是基于 Ribbon 实现的,因此它自带了客户端负载均衡功能,也能够经过 Ribbon 的 IRule 进行策略扩展。另外,Feign 还整合的 Hystrix 来实现服务的容错保护,这个在后边会详细讲。

验证是否调用成功

GET http://192.168.2.102:9002/area?length=1&width=2&heigh=3

HTTP/1.1 200 
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 19 Nov 2018 06:57:52 GMT

22

Response code: 200; Time: 525ms; Content length: 2 bytes
相关文章
相关标签/搜索