天天看点

SpringCloud组件之Feign

Feign是一个声明式的Web服务客户端。这使得Web服务客户端的写入更加方便 要使用Feign创建一个界面并对其进行注释。它具有可插拔注释支持,包括Feign注释和JAX-RS注释。Feign还支持可插拔编码器和解码器。Spring Cloud添加了对Spring MVC注释的支持,并在Spring Web中使用默认使用的HttpMessageConverters。Spring Cloud集成Ribbon和Eureka以在使用Feign时提供负载均衡的http客户端

本文将介绍Feign的原理和一些相关知识点以及如何在项目中使用

一、Feign的原理

1、启动时,程序会进行包扫描,扫描所有包下所有@FeignClient注解的类,并将这些类注入到spring的IOC容器中。当定义的Feign中的接口被调用时,通过JDK的动态代理来生成RequestTemplate。

2、RequestTemplate中包含请求的所有信息,如请求参数,请求URL等

3、RequestTemplate生成Request,然后将Request交给client处理,这个client默认是JDK的HTTPUrlConnection,也可以是OKhttp、Apache的HTTPClient等

4、最后client封装成LoadBaLanceClient,结合ribbon负载均衡地发起调用

SpringCloud组件之Feign

二、项目中使用

1、搭建Eureka注册中心

本文不介绍如何搭建Eureka服务,不了解Eureka的可以前往查看这篇文章学习:

SpringCloud组件之Eureka

2、搭建目标服务

a、导入依赖

<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、启动类标注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、编写接口,提供给Feign调用

/**
 * @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、搭建调用服务

<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、启动类增加注解

/**
 * @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、创建service,用于调用服务

/**
 * @author Gjing
 **/
@FeignClient(name = "demo")
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);
}           

e、编写Controller进行测试访问

/**
 * @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如何进行回退处理

Feign本身集成了Hystrix,因此,我们直接在启动类加上

@EnableCircuitBreaker

即可,对Hystrix不了解的可以前往这篇文章:

SpringCloud组件之Hystrix

a、pom文件增加依赖,否则会Hystrix出错

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

@EnableCircuitBreaker

c、yml文件开启Hystrix保护

feign:
  hystrix:
    enabled: true           

d、创建回退类并实现之前的Feign接口类

/**
 * @author Gjing
 **/
@Component
public class FeignTestFallbackImpl implements FeignTestService {
    @Override
    public Map<String, Object> test() {
        // TODO: 2019/7/3 这里就实现回退后的处理咯 
        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接口类,设置回退类

/**
 * @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、调用测试

如果出现超时或者异常,将进行回退处理

SpringCloud组件之Feign

本文到此就结束了,如果发现有误欢迎指正哦,Feign默认是使用HttpUrlConnection进行http请求的,还支持okHttp和httpClient的哈,这些用法大家自行研究,本文不作介绍了,如果有兴趣了解另一种使用Feign,可以参考我这篇文章:

SpringCloud-Feign

,Demo源代码地址:

SpringCloud-Demo