feign简单介绍和使用

329 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第21天,点击查看活动详情

feign简单介绍和使用

介绍:

微服务开发中通常由于各个服务之间在物理上可能是互相隔离,各种资源分布在不同的服务中,每个服务对应着各自的数据库,因此当A服务想要调用B或者其他服务的资源时可以通过远程http请求的方式,获得别的服务资源使用,在这一过程中可以使用远程调用框架feign;

​ Feign是一款轻量级RESTful的HTTP服务客户端远程调用框架,相比较于传统上的Http封装接口,它以Java接⼝注解的⽅式调⽤Http请求,一般微服务开发中,服务间的接口调用使用。 类似于Dubbo,消费端请求服务端提供的远程调用接口,然后像调⽤本地接⼝⽅法⼀样 去调⽤,实际发出的是远程的请求。

同时他也继承了Hystrix和ribbon的的功能;

使用:

1、引入依赖:

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

2、在Springboot启动类上加注解指定哪个包下开启远程调用

​ @EnableFeignClients(basePackages = "com.vv.blog.member.feign")

@EnableFeignClients(basePackages = "com.vv.blog.member.feign")
/*@Data
@RefreshScope*/
@EnableDiscoveryClient
@SpringBootApplication(exclude= DataSourceAutoConfiguration.class)
public class BlogMemberApplication {

3、 服务端创建Controller

@RestController
public class TestController {
   @GetMapping("test")
   public String remoteFeign() throws InterruptedException {
      Thread.sleep(5000);
      return "success";
   }

sleep为了模拟服务降级处理;

4、消费端创建调用接口

@FeignClient(name = "blog-member",fallback = BlogMemberServiceImpl.class)
public interface BlogMemberService {

   @GetMapping("test")
    String remoteFeign();
}

@FeignClient注解的name属性⽤于指定要调⽤的服务提供者名称,yu服务提供者yml⽂件中spring.application.name保持⼀致;fallback指定服务降级的实现类;

5、服务降级接口处理

实现指定接口,实现降级逻辑;

配置文件:

##开启降级熔断
feign:
  hystrix:
    enabled: true
hystrix:
  command:
    default:
      execution:
        isolation:
          thread:
            timeoutInMilliseconds: 3000
@Component
public class BlogMemberServiceImpl implements BlogMemberService {

   @Override
   public String remoteFeign() {
      return "fails";
   }
}

结果:

GET http://localhost:10001/get

HTTP/1.1 200 Content-Type: text/plain;charset=UTF-8 Content-Length: 5 Date: Tue, 21 Jun 2022 05:59:09 GMT Keep-Alive: timeout=60 Connection: keep-alive

降级结果========》》》》》》fails

超时大约3秒

Response code: 200; Time: 3817ms; Content length: 5 bytes

Feign支持请求压缩和响应压缩的

Feign ⽀持对请求和响应进⾏GZIP压缩,以减少通信过程中的性能损耗。

配置:

feign:
  hystrix:
    enabled: true
  compression:
    request:
      enabled: true
      mime-types: text/html,application/xml,application/json  #压缩文件类型
      min-request-size: 2048 #默认值
    response:
      enabled: true
     # useGzipDecoder: true

Feign的日志级别配置

Feign是http请求客户端,当使用feign请求和接收响应的时候,可以通过一些配置打印出⽐较详细的⼀些⽇志信息(响应头,服务状态code,请求时长等等等),默认情况下Feign的⽇志 没有开启。

Feign的⽇志级别

  • NONE:默认的,性能最好 ,不打印任何日志输出
  • BASIC:仅记录请求⽅法、URL、响应状态码以及执⾏时间----⽣产问题追踪
  • HEADERS:在BASIC级别的基础上,记录请求和响应的header
  • FULL:记录请求和响应的header、body和元数据,适⽤于开发及测试环境定位问题
@Configuration
public class FeignConfig {

   @Bean
   Logger.Level feignLevel(){
      return Logger.Level.BASIC;
   }
}