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
相關文章
相關標籤/搜索