SpringCloud系列六:Feign接口轉換調用服務(Feign 基本使用、Feign 相關配置)


聲明:本文來源於MLDN培訓視頻的課堂筆記,寫在這里只是為了方便查閱。

1、概念:Feign 接口服務

2、具體內容

現在為止所進行的所有的 Rest 服務調用實際上都會出現一個非常尷尬的局面,例如:以如下代碼為例:

Dept dept = this.restTemplate
                .exchange(DEPT_GET_URL + id, HttpMethod.GET,
                        new HttpEntity<Object>(this.headers), Dept.class)
                .getBody();

所有的數據的調用和轉換都必須由用戶自己來完成,而我們本身不擅長這些,我們習慣的編程模式是:通過接口來實現業務的操作,而不是通過具體的 Rest 數據。

2.1、Feign 基本使用

為了方便起見現在將“microcloud-consumer-80”模塊復制為了“microcloud-consumer-feign”模塊。

1、 【microcloud-consumer-feign】為了可以使用到 feign 支持,需要修改 pom.xml 配置文件,引入相關依賴包:

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

feign 包含了 Ribbon 支持,所以導入了以上的依賴包之后就表示項目之中已經存在有了 ribbon 相關支持庫。

2、 【microcloud-service】建立一個新的模塊,這個模塊專門負責客戶端接口的定義;

3、 【microcloud-service】修改 pom.xml 配置文件,引用“microcloud-api”模塊,這樣就可以使用到 VO 類了;

        <dependency>
            <groupId>cn.study</groupId>
            <artifactId>microcloud-api</artifactId>
        </dependency>

4、 【microcloud-service】此時如果要通過 Feign 進行遠程 Rest 調用,那么必須要考慮服務的認證問題。

· 此時可以刪除原始的 RestConfig 進行的配置處理,然后添加feign的認證配置類

package cn.study.commons.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.auth.BasicAuthRequestInterceptor;
@Configuration
public class FeignClientConfig {
    @Bean
    public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("studyjava", "hello");
    }
}

5、 【microcloud-service】建立一個 IDeptClientService 接口;

package cn.study.service;

import java.util.List;

import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import cn.study.commons.config.FeignClientConfig;
import cn.study.vo.Dept;
/**
 * 通過注解@FeignClient添加接口對應的遠程微服務名稱value="MICROCLOUD-PROVIDER-DEPT"和
 * 服務的認證configuration=FeignClientConfig.class
 *
 */
@FeignClient(value="MICROCLOUD-PROVIDER-DEPT",configuration=FeignClientConfig.class)
public interface IDeptClientService {
    @RequestMapping(method=RequestMethod.GET,value="/dept/get/{id}")
    public Dept get(@PathVariable("id") long id) ;
    @RequestMapping(method=RequestMethod.GET,value="/dept/list")
    public List<Dept> list() ;
    @RequestMapping(method=RequestMethod.POST,value="/dept/add")
    public boolean add(Dept dept) ;
}

6、 【microcloud-consumer-feign】修改 pom.xml 配置文件,引入 microcloud-service 開發包:

        <dependency>
            <groupId>cn.study</groupId>
            <artifactId>microcloud-service</artifactId>
        </dependency>

7、 【microcloud-consumer-feign】修改 ConsumerDeptController 控制器程序類;

package cn.study.microcloud.controller;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.study.service.IDeptClientService;
import cn.study.vo.Dept;

@RestController
public class ConsumerDeptController {
    @Resource
    private IDeptClientService deptService ;
    @RequestMapping(value = "/consumer/dept/get")
    public Object getDept(long id) {
        return this.deptService.get(id);
    }
    @RequestMapping(value = "/consumer/dept/list")
    public Object listDept() {
        return this.deptService.list();
    }
    @RequestMapping(value = "/consumer/dept/add")
    public Object addDept(Dept dept) throws Exception {
        return this.deptService.add(dept);
    }
}

8、 【microcloud-consumer-feign】修改程序啟動主類,追加操作處理。

package cn.study.microcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.feign.EnableFeignClients;
@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients(basePackages={"cn.study.service"})//進行接口IDeptClientService的掃描生成使得可以注入到ConsumerDeptController里面
public class Consumer_80_StartSpringCloudApplication {
    public static void main(String[] args) {
        SpringApplication.run(Consumer_80_StartSpringCloudApplication.class,
                args);
    }
}

9、 啟動測試:http://client.com/consumer/dept/get?id=1

· 可以發現 Feign 在處理的時候自帶有負載均衡的配置項

2.2、Feign 相關配置

1、 【microcloud-consumer-feign】Feign 之中最為核心的作用就是將 Rest 服務的信息轉換為接口,但是在實際的使用之中也需要考慮到一些配置情況,例如:數據壓縮,Rest 的核心本質在於:JSON 數據傳輸(XML、文本),於是就必須思考一種情況,如果用戶發送的數據很大,這個時候可以考慮修改 application.yml 配置文件對傳輸數據進行壓縮;

feign:
  compression:
    request:
      mime-types:       # 可以被壓縮的類型
      - text/xml
      - application/xml
      - application/json
      min-request-size: 2048 # 超過2048的字節進行壓縮

2、 如果有需要則可以在項目之中開啟 feign 的相關日志信息(默認不開啟):

· 【microcloud-consumer-feign】修改 application.yml 配置文件,追加日志追蹤:

logging:
  level:
    cn.study.service: DEBUG

· 【microcloud-service】修改 FeignClientConfig,開啟日志的輸出:

package cn.study.commons.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import feign.Logger;
import feign.auth.BasicAuthRequestInterceptor;
@Configuration
public class FeignClientConfig {
    @Bean public Logger.Level getFeignLoggerLevel() {
        return feign.Logger.Level.FULL ; } @Bean
    public BasicAuthRequestInterceptor getBasicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("studyjava", "hello");
    }
}

再次運行程序現在可以觀察到如下的流程:

· 當使用 Feign 要通過接口的方法訪問 Rest 服務的時候會根據設置的服務類型發出請求,這個請求是發送給 Eureka(地址: “http://MICROCLOUD-PROVIDER-DEPT/dept/list”);

· 隨后由於配置了授權處理,所以繼續發送授權信息(“Authorization”);

· 在進行服務調用的時候 Feign 融合了 Ribbon 技術,所以也支持有負載均衡的處理;

總結:Feign = RestTempate + HttpHeader + Ribbon + Eureka 綜合體 = 業務接口的自動實例化


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM