SpringCloud組件之Feign

Feign是一個(gè)聲明式的Web服務(wù)客戶端。這使得Web服務(wù)客戶端的寫(xiě)入更加方便 要使用Feign創(chuàng)建一個(gè)界面并對(duì)其進(jìn)行注釋。它具有可插拔注釋支持,包括Feign注釋和JAX-RS注釋。Feign還支持可插拔編碼器和解碼器。Spring Cloud添加了對(duì)Spring MVC注釋的支持,并在Spring Web中使用默認(rèn)使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign時(shí)提供負(fù)載均衡的http客戶端

本文將介紹Feign的原理和一些相關(guān)知識(shí)點(diǎn)以及如何在項(xiàng)目中使用

一、Feign的原理

1、啟動(dòng)時(shí),程序會(huì)進(jìn)行包掃描,掃描所有包下所有@FeignClient注解的類,并將這些類注入到spring的IOC容器中。當(dāng)定義的Feign中的接口被調(diào)用時(shí),通過(guò)JDK的動(dòng)態(tài)代理來(lái)生成RequestTemplate。
2、RequestTemplate中包含請(qǐng)求的所有信息,如請(qǐng)求參數(shù),請(qǐng)求URL等
3、RequestTemplate生成Request,然后將Request交給client處理,這個(gè)client默認(rèn)是JDK的HTTPUrlConnection,也可以是OKhttp、Apache的HTTPClient等
4、最后client封裝成LoadBaLanceClient,結(jié)合ribbon負(fù)載均衡地發(fā)起調(diào)用


1562133752(1).jpg

二、項(xiàng)目中使用

1、搭建Eureka注冊(cè)中心

本文不介紹如何搭建Eureka服務(wù),不了解Eureka的可以前往查看這篇文章學(xué)習(xí):SpringCloud組件之Eureka

2、搭建目標(biāo)服務(wù)

a、導(dǎo)入依賴

<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>

b、啟動(dòng)類標(biāo)注Eureka客戶端注解

/**
 * @author Gjing
 */
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

c、yml文件配置

server:
  port: 8090
spring:
  application:
    name: demo
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

d、編寫(xiě)接口,提供給Feign調(diào)用

/**
 * @author Gjing
 **/
@RestController
public class TestController {

    @GetMapping("/test")
    public Map<String,Object>test() {
        Map<String,Object> map = new HashMap<>(16);
        map.put("code", "ok");
        return map;
    }

    @GetMapping("/test2")
    public String test2(@RequestParam(name = "param1") String param1) {
        return param1;
    }

    @PostMapping("/test3")
    public Integer test3(Integer id) {
        return id;
    }
}

3、搭建調(diào)用服務(wù)

a、導(dǎo)入依賴

<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.cloud</groupId>
     <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

b、啟動(dòng)類增加注解

/**
 * @author Gjing
 */
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class FeignApplication {

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

}

c、yml配置

server:
  port: 8083
spring:
  application:
    name: feign-demo
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

d、創(chuàng)建service,用于調(diào)用服務(wù)

/**
 * @author Gjing
 **/
@FeignClient(name = "demo")
public interface FeignTestService {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    Map<String,Object>test();

    @RequestMapping(value = "test2", method = RequestMethod.GET)
    String test2(@RequestParam("param1") String param1);

    @RequestMapping(value = "/test3", method = RequestMethod.POST)
    Integer test3(@RequestParam("id") Integer id);
}

e、編寫(xiě)Controller進(jìn)行測(cè)試訪問(wèn)

/**
 * @author Gjing
 **/
@RestController
public class FeignTestController {

    @Resource
    private FeignTestService feignTestService;

    @GetMapping("/test")
    public String test() {
        return feignTestService.test().toString();
    }

    @GetMapping("/test2")
    public ResponseEntity test2() {
        String test2 = feignTestService.test2("你好");
        return ResponseEntity.ok(test2);
    }

    @GetMapping("/test3")
    public ResponseEntity test3() {
        Integer test3 = feignTestService.test3(1);
        return ResponseEntity.ok(test3);
    }
}

4、Feign如何進(jìn)行回退處理

Feign本身集成了Hystrix,因此,我們直接在啟動(dòng)類加上@EnableCircuitBreaker即可,對(duì)Hystrix不了解的可以前往這篇文章:SpringCloud組件之Hystrix

a、pom文件增加依賴,否則會(huì)Hystrix出錯(cuò)

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

b、啟動(dòng)類增加注解@EnableCircuitBreaker

c、yml文件開(kāi)啟Hystrix保護(hù)

feign:
  hystrix:
    enabled: true

d、創(chuàng)建回退類并實(shí)現(xiàn)之前的Feign接口類

/**
 * @author Gjing
 **/
@Component
public class FeignTestFallbackImpl implements FeignTestService {
    @Override
    public Map<String, Object> test() {
        // TODO: 2019/7/3 這里就實(shí)現(xiàn)回退后的處理咯 
        Map<String,Object> map = new HashMap<>(16);
        map.put("code", "回退了");
        return map;
    }
    
    @Override
    public String test2(String param1) {
        return null;
    }

    @Override
    public Integer test3(Integer id) {
        return null;
    }
}

e、修改feign接口類,設(shè)置回退類

/**
 * @author Gjing
 **/
@FeignClient(name = "demo",fallback = FeignTestFallbackImpl.class)
public interface FeignTestService {

    @RequestMapping(value = "/test", method = RequestMethod.GET)
    Map<String,Object> test();

    @RequestMapping(value = "test4", method = RequestMethod.GET)
    String test2(@RequestParam("param1") String param1);

    @RequestMapping(value = "/test3", method = RequestMethod.POST)
    Integer test3(@RequestParam("id") Integer id);
}

f、調(diào)用測(cè)試

如果出現(xiàn)超時(shí)或者異常,將進(jìn)行回退處理

1562137157(1).jpg


本文到此就結(jié)束了,如果發(fā)現(xiàn)有誤歡迎指正哦,F(xiàn)eign默認(rèn)是使用HttpUrlConnection進(jìn)行http請(qǐng)求的,還支持okHttp和httpClient的哈,這些用法大家自行研究,本文不作介紹了,如果有興趣了解另一種使用Feign,可以參考我這篇文章:SpringCloud-Feign,Demo源代碼地址:SpringCloud-Demo

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容