spring cloud feign學(xué)習(xí)二:Feign的深入使用

覆蓋Feign的默認(rèn)配置

A central concept in Spring Cloud’s Feign support is that of the named client. Each feign client is part of an ensemble of components that work together to contact a remote server on demand, and the ensemble has a name that you give it as an application developer using the @FeignClient annotation. Spring Cloud creates a new ensemble as an ApplicationContext on demand for each named client using FeignClientsConfiguration. This contains (amongst other things) an feign.Decoder, a feign.Encoder, and a feign.Contract.

Spring Cloud的Feign支持的一個中心概念就是命名客戶端墨技。 每個Feign客戶端都是組合的組件的一部分放椰,它們一起工作以按需調(diào)用遠(yuǎn)程服務(wù)器缔刹,并且該集合具有您將其作為使用@FeignClient注釋的參數(shù)名稱。 Spring Cloud使用FeignClientsConfiguration創(chuàng)建一個新的集合作為每個命名客戶端的ApplicationContext(應(yīng)用上下文)杀迹。 這包含(除其他外)feign.Decoder亡脸,feign.Encoderfeign.Contract

你可以自定義FeignClientsConfiguration以完全控制這一系列的配置树酪。比如我們下面的demo:

定義一個order服務(wù)梗掰,并加入依賴:

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>

定義主體啟動類:

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
public class OrderApplication {
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class,args);
    }
}

定義Controller:

@RestController
@RequestMapping("/order")
public class OrderController {

    private Logger logger = LoggerFactory.getLogger(getClass());


    @Autowired
    UserService userService;

    @RequestMapping("/index")
    public String index(){
        logger.info("index方法");
        return userService.index();
    }
}

定義Feign客戶端接口:

@FeignClient(value = "user-service",configuration = FooConfiguration.class)
public interface UserService {

    @RequestLine("GET /user/index")
    String index();

}

使用了配置@Configuration參數(shù),自己定義了FooConfiguration類來自定義FeignClientsConfiguration嗅回,并且FeignClientsConfiguration類的類路徑不在啟動類OrderApplication的掃描路徑下及穗,是因為如果在掃描目錄下會覆蓋該項目所有的Feign接口的默認(rèn)配置。

FooConfiguration定義:

package com.zhihao.miao.config;

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

@Configuration
public class FooConfiguration {

    //使用Feign自己的注解绵载,使用springmvc的注解就會報錯
    @Bean
    public Contract feignContract() {
        return new feign.Contract.Default();
    }
}

因為配置FooConfiguration定義的是new feign.Contract.Default()埂陆,所有在UserService接口中只能使用Feign自己的注解url方式。

配置文件:

spring:
  application:
    name: order-service
eureka:
  client:
    service-url:
     defaultZone: http://zhihao.miao:123456@localhost:8761/eureka
  instance:
    instance-id:  ${spring.application.name}:${spring.cloud.client.ipAddress}:${spring.application.instance_id:${server.port}}
server:
  port: 9090

訪問http://192.168.5.3:9090/order/index娃豹,正常訪問到結(jié)果焚虱。

再定義一個FeignClient接口,使用SpringMvc注解的方式來訪問

@FeignClient(value = "eureka-service",url = "http://localhost:8761/",configuration = EurekaConfiguration.class)
public interface EurekaService {

    @RequestMapping(value = "/eureka/apps/{serviceName}")
    String findServiceInfoFromEurekaByServiceName(@PathVariable("serviceName") String serviceName);
}

因為Eureka配置了用戶名和密碼懂版,所有這個FeignClient也自己定義了FeignClientsConfiguration鹃栽,也可以用來訪問Eureka服務(wù)接口。

package com.zhihao.miao.config;

import feign.auth.BasicAuthRequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EurekaConfiguration {

    @Bean
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor("zhihao.miao", "123456");
    }
}

通過訪問http://192.168.5.3:9090/order/findServiceInfoFromEurekaByServiceName/user-service也能訪問成功躯畴,通過這個列子我們知道可以為每個Feign客戶端都配置了自己的默認(rèn)配置民鼓。

注意

  • @FeignClient注解的serviceId參數(shù)不建議被使用薇芝。
  • 以前使用@FeignClient注解的時候使用url參數(shù)的使用就不需要使用name屬性了,現(xiàn)在不然丰嘉,需要在url屬性的基礎(chǔ)上也要使用name屬性夯到,此時的name屬性只是一個標(biāo)識。

參考資料

springcloud 官網(wǎng)
feign的github地址

參數(shù)綁定

在快速入門中饮亏,我們使用了spring cloud feign實現(xiàn)的是一個不帶參數(shù)的REST服務(wù)綁定∷<郑現(xiàn)實中的各種業(yè)務(wù)接口要比它復(fù)雜的多,我們會在http的各個位置傳入各種不同類型的參數(shù)路幸,并且在返回請求響應(yīng)的時候也可能是一個復(fù)雜的對象結(jié)構(gòu)荐开。

擴展一下user-servcice服務(wù),增加一些接口定義简肴,其中包含Request參數(shù)的請求晃听,帶有Header信息的請求,帶有RequestBody的請求以及請求響應(yīng)體中是一個對象的請求,擴展了三個接口分別是hello着帽,hello2,hello3

@RestController
@RequestMapping("/user")
public class UserController {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private DiscoveryClient client;

    @RequestMapping(value="/index",method = RequestMethod.GET)
    public String index(){
        ServiceInstance instance = client.getLocalServiceInstance();
        logger.info("/user,host:"+instance.getHost()+",service id:"+instance.getServiceId()+",port:"+instance.getPort());
        return "user index, local time="+ LocalDateTime.now();
    }

    @GetMapping("/hello")
    public String userHello() throws Exception{
        ServiceInstance serviceInstance = client.getLocalServiceInstance();
        //線程阻塞
        int sleeptime = new Random().nextInt(3000);
        logger.info("sleeptime:"+sleeptime);
        Thread.sleep(sleeptime);
        logger.info("/user,host:"+serviceInstance.getHost()+",service id:"+serviceInstance.getServiceId()+",port:"+serviceInstance.getPort());
        return "user hello";
    }

    @RequestMapping(value = "/hello1",method = RequestMethod.GET)
    public String hello(@RequestParam String username){
        return "hello "+username;
    }

    @RequestMapping(value = "hello2",method = RequestMethod.GET)
    public User hello2(@RequestHeader String username,@RequestHeader Integer age){
        return new User(username,age);
    }

    @RequestMapping(value = "hello3",method = RequestMethod.POST)
    public String hello3(@RequestBody User user){
        return "hello "+user.getUsername() +", "+user.getAge()+", "+user.getId();
    }
}

訪問:

localhost:8080/user/hello1?username=zhihao.miao

User對象的定義如下移层,需要注意的是要有User的默認(rèn)的構(gòu)造函數(shù)仍翰,不然,spring cloud feign根據(jù)json字符串轉(zhuǎn)換User對象的時候會拋出異常观话。

public class User {
    private String username;

    private int age;

    private int id;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public User(String username, int age) {
        this.username = username;
        this.age = age;
    }

    public User() {

    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", age=" + age +
                ", id=" + id +
                '}';
    }
}

完成對user-service的改造之后予借,我們對pay-service進行改造:

  • user-service中創(chuàng)建與上面一樣的User類
  • pay-service中的UserService接口中加入之前的接口定義:
@FeignClient("user-service")
public interface UserService {

    @RequestMapping("/user/index")
    String index();

    @RequestMapping("/user/hello")
    String hello();

    @RequestMapping(value = "/user/hello1",method = RequestMethod.GET)
    String hello1(@RequestParam("username") String username);

    @RequestMapping(value = "/user/hello2",method = RequestMethod.GET)
    User hello2(@RequestHeader("username") String username, @RequestHeader("age") Integer age);

    @RequestMapping(value = "/user/hello3",method = RequestMethod.POST)
    String hello3(@RequestBody User user);
}

注意
在定義各參數(shù)綁定的時候,@RequestParam@RequestHeader等可以指定參數(shù)名稱的注解频蛔,它們的value值千萬不能少灵迫。在spring mvc程序中,這些注解會根據(jù)指定參數(shù)名來作為默認(rèn)值晦溪,但是在fegin中綁定參數(shù)必須通過value屬性來指明具體的參數(shù)名瀑粥,不然會拋出IllegalStateException異常,value屬性不能為空三圆。

  • 在payservice中增加對UserService中新增接口的調(diào)用狞换,來驗證feign客戶端的調(diào)用是否可行:
@RestController
@RequestMapping("/pay")
public class PayController {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    UserService userService;

    @RequestMapping("/index")
    public String index(){
        return userService.index();
    }

    @RequestMapping("/hello")
    public String hello(){
        return userService.hello();
    }

    @RequestMapping(value = "/hello1",method = RequestMethod.GET)
    public String hello1(@RequestParam String username){
        return userService.hello1(username);
    }

    @RequestMapping(value = "/hello2",method = RequestMethod.GET)
    public User hello2(@RequestHeader String username,@RequestHeader Integer age){
        logger.info(age.getClass().getName());
        return userService.hello2(username,age);
    }

    @RequestMapping(value = "/hello3",method = RequestMethod.POST)
    public String hello3(@RequestBody User user){
        return userService.hello3(user);
    }
}

測試,

localhost:7070/pay/hello1?username=zhihao.miao
localhost:7070/pay/hello2
localhost:7070/pay/hello3
圖片.png

繼承特性

通過上面的快速入門和參數(shù)綁定二個demo舟肉,當(dāng)使用springmvc的注解來綁定服務(wù)接口時候修噪,我們幾乎可以完全從服務(wù)提供方(user-service)的Controller中依靠復(fù)制操作,構(gòu)建出相應(yīng)的服務(wù)客戶端綁定接口路媚。既然存在這么多復(fù)制操作黄琼,我們自然需要考慮這部分內(nèi)容是否可以得到進一步的抽象。spring cloud feign中整慎,針對該問題提供了繼承特性來幫助我們解決這些復(fù)制操作脏款,以進一步減少編碼量围苫。

  • 定義一個maven工程,user-service-api
  • 由于在user-service-api中需要定義可同時復(fù)用于服務(wù)端與客戶端的接口弛矛,需要用到spring mvc的注解够吩,所以在pom.xml中引入spring-boot-starter-web依賴,具體的內(nèi)容如下:
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • 將之前的User對象復(fù)制到自己的項目中丈氓,創(chuàng)建UserService接口周循,內(nèi)容如下:
 @RequestMapping("/refactor")
public interface UserService {

    @RequestMapping(value = "/hello4",method = RequestMethod.GET)
    String hello1(@RequestParam("username") String username);

    @RequestMapping(value = "/hello5",method = RequestMethod.GET)
    User hello2(@RequestHeader("username") String username, @RequestHeader("age") Integer age);

    @RequestMapping(value = "/hello6",method = RequestMethod.POST)
    String hello3(@RequestBody User user);
}
  • 對user-service進行重構(gòu),在pom依賴中加入user-service-api的依賴:
 <dependency>
       <groupId>com.zhihao.miao</groupId>
       <artifactId>user-service-api</artifactId>
       <version>1.0-SNAPSHOT</version>
</dependency>
  • 創(chuàng)建com.zhihao.miao.user.controller.RefactorUserController繼承user-service中的UserService接口万俗,實現(xiàn)如下:
@RestController
public class RefactorUserController implements UserService{

    @Override
    public String hello1(@RequestParam String username) {
        return "user "+username;
    }

    @Override
    public User hello2(@RequestHeader("username")  String username, @RequestHeader("age") Integer age) {
        return new User(username,age);
    }

    @Override
    public String hello3(@RequestBody User user) {
        return "user "+user.getUsername()+", "+user.getAge();
    }
}

我們看到可以通過集成的方式湾笛,在Controller中不再包含以往會定義的映射注解@RequestMapping,而參數(shù)的注解定義在重寫的時候自動帶過來了闰歪,這個類中嚎研,除了要實現(xiàn)接口邏輯之外,只需要增加了@RestController注解使該類成為一個REST接口類库倘。

此時這些restful接口的接口url就是user-service-api中定義的临扮,具體的uri地址是/refactor/hello4/refactor/hello5教翩,/refactor/hello6

  • 完成了對服務(wù)提供者的重構(gòu)杆勇,在消費端的pay-service中也要進行改造,在pay-service中加入如下依賴:
<dependency>
       <groupId>com.zhihao.miao</groupId>
       <artifactId>user-service-api</artifactId>
       <version>1.0-SNAPSHOT</version>
</dependency>
  • 創(chuàng)建RefactorUserService,繼承user-service-apiUserService接口饱亿,然后添加@FeignClient來綁定服務(wù)蚜退。
@FeignClient(value = "user-service")
public interface RefactorUserService extends com.zhihao.miao.service.UserService{
    
}
  • PayController2中注入RefactorUserService實例,新增restful接口進行訪問:
@RestController
@RequestMapping("/pay2")
public class PayController2 {

    @Autowired
    RefactorUserService refactorUserService;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping(value = "/hello1",method = RequestMethod.GET)
    public String hello4(@RequestParam String username){
        return refactorUserService.hello1(username);
    }

    @RequestMapping(value = "/hello2",method = RequestMethod.GET)
    public User hello5(@RequestHeader String username, @RequestHeader Integer age){
        logger.info(age.getClass().getName());
        return refactorUserService.hello2(username,age);
    }

    @RequestMapping(value = "/hello3",method = RequestMethod.POST)
    public String hello6(@RequestBody User user){
        return refactorUserService.hello3(user);
    }
}
  • 測試:

訪問user-service服務(wù):localhost:8080/refactor/hello4?username=zhihao.miao

測試pay-service:

localhost:7070/pay/hello1?username=zhihao.miao
圖片.png
圖片.png

優(yōu)點與缺點
使用spring cloud feign的繼承特性的優(yōu)點很明顯彪笼,可以將接口的定義從Controller中剝離钻注,同時配合maven倉庫就可以輕易實現(xiàn)接口定義的共享,實現(xiàn)在構(gòu)建期的接口綁定配猫,從而有效的減少服務(wù)客戶端的綁定配置幅恋。這么做雖然可以很方便的實現(xiàn)接口定義和依賴的共享,不用在復(fù)制粘貼接口進行綁定泵肄,但是這樣的做法使用不當(dāng)?shù)脑挄砀弊饔眉亚病S捎诮涌谠跇?gòu)建期間就建立起了依賴,那么接口變化就會對項目構(gòu)建造成了影響凡伊,可能服務(wù)提供方修改一個接口定義零渐,那么會直接導(dǎo)致客戶端工程的構(gòu)建失敗。所以系忙,如果開發(fā)團隊通過此方法來實現(xiàn)接口共享的話诵盼,建議在開發(fā)評審期間嚴(yán)格遵守面向?qū)ο蟮拈_閉原則,盡可能低做好前后版本兼容,防止因為版本原因造成接口定義的不一致风宁。

代碼地址
代碼地址

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末洁墙,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子戒财,更是在濱河造成了極大的恐慌热监,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,372評論 6 498
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件饮寞,死亡現(xiàn)場離奇詭異孝扛,居然都是意外死亡,警方通過查閱死者的電腦和手機幽崩,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,368評論 3 392
  • 文/潘曉璐 我一進店門苦始,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人慌申,你說我怎么就攤上這事陌选。” “怎么了蹄溉?”我有些...
    開封第一講書人閱讀 162,415評論 0 353
  • 文/不壞的土叔 我叫張陵咨油,是天一觀的道長。 經(jīng)常有香客問我柒爵,道長役电,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,157評論 1 292
  • 正文 為了忘掉前任餐弱,我火速辦了婚禮宴霸,結(jié)果婚禮上囱晴,老公的妹妹穿的比我還像新娘膏蚓。我一直安慰自己,他們只是感情好畸写,可當(dāng)我...
    茶點故事閱讀 67,171評論 6 388
  • 文/花漫 我一把揭開白布驮瞧。 她就那樣靜靜地躺著,像睡著了一般枯芬。 火紅的嫁衣襯著肌膚如雪论笔。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,125評論 1 297
  • 那天千所,我揣著相機與錄音狂魔,去河邊找鬼。 笑死淫痰,一個胖子當(dāng)著我的面吹牛最楷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,028評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼籽孙,長吁一口氣:“原來是場噩夢啊……” “哼烈评!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起犯建,我...
    開封第一講書人閱讀 38,887評論 0 274
  • 序言:老撾萬榮一對情侶失蹤讲冠,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后适瓦,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體竿开,經(jīng)...
    沈念sama閱讀 45,310評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,533評論 2 332
  • 正文 我和宋清朗相戀三年犹菇,在試婚紗的時候發(fā)現(xiàn)自己被綠了德迹。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,690評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡揭芍,死狀恐怖胳搞,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情称杨,我是刑警寧澤肌毅,帶...
    沈念sama閱讀 35,411評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站姑原,受9級特大地震影響悬而,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜锭汛,卻給世界環(huán)境...
    茶點故事閱讀 41,004評論 3 325
  • 文/蒙蒙 一笨奠、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧唤殴,春花似錦般婆、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至配名,卻和暖如春啤咽,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背渠脉。 一陣腳步聲響...
    開封第一講書人閱讀 32,812評論 1 268
  • 我被黑心中介騙來泰國打工宇整, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人芋膘。 一個月前我還...
    沈念sama閱讀 47,693評論 2 368
  • 正文 我出身青樓鳞青,卻偏偏與公主長得像涩哟,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子盼玄,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,577評論 2 353

推薦閱讀更多精彩內(nèi)容