Fegin基础知识

文章介绍了Fegin的基本概念,作为Netflix的一个声明式HTTP客户端,以及它如何被SpringCloud的OpenFeign增强,支持SpringMVC注解和Ribbon、Nacos的整合。此外,文中还提到了OpenFeign的使用示例,包括服务调用、日志配置、超时时间和自定义拦截器的设置。
摘要由CSDN通过智能技术生成

Fegin

Fegin和OpenFegin的区别:

Fegin是Netflix开发的声明式,模板化的Http客户端,可以帮助我们更加敏捷,优雅地调用Http API。Fegin支持多种注解,例如Fegin自带的注解或者JAX-RS注解等,需要单独学习这些注解。目前已经闭源。

OpenFeign是Spring Cloud 对Fegin进行了增强,使其支持Spring MVC注解,还整合了Ribbon和Nacos,从而使Fegin的使用更加的方便。

Spring Cloud Alibaba整合OpenFeign

  1. 添加依赖

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    
  2. 启动类添加@EnableFeignClients注解

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

    import com.kiwi.order.feign.Impl.StockFeignServiceFallback;
    import org.springframework.cloud.openfeign.FeignClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    // 说明:fallbackFactory在集成sentinel之后可以实现一个异常回调的作用
    @FeignClient(value = "stock-service",path = "/stock",fallbackFactory = StockFeignServiceFallback.class)
    public interface StockFeignService {
    
        @RequestMapping("/deduct")
        String deduct();
    
    }
    
  4. 服务消费方调用服务

    @RestController
    @RequestMapping("/order")
    public class OrderController {
    
        //这里注入的是Order-service这个工程中定义的StockFeignService
        @Resource
        StockFeignService stockFeignService;
    
    
        @RequestMapping("/add")
        public String add(){
            System.out.println("下单成功");
            //像调用本地服务一样调用其他服务
            String msg = stockFeignService.deduct();
            return "spring Cloud openFeign Hello world!" + msg;
        }
    
    }
    

开启OpenFeign日志

  1. 添加配置类
    OpenFeign提供四种日志级别:

    • NONE【性能最佳,适用于生产】:不记录任何日志(默认值)。
    • BASIC【适用于生产环境追踪问题】:仅记录请求方法、URL、响应状态代码以及 执行时间。
    • HEADERS:记录BASIC级别的基础上,记录请求和响应的header。
    • FULL【比较适用于开发及测试环境定位问题】:记录请求和响应的header、body 和元数据。
    // 全局配置:使用@Configuration会作用到所有的服务提供方
    // 局部配置:如果只想针对某一个服务进行配置,就不要加@Configuration,然后再@FeignClient上用configuration属性指定FeignConfig
    //@Configuration
    public class FeignConfig {
    
        @Bean
        public Logger.Level feignLoggerLevel(){
            return Logger.Level.FULL;
        }
    
    }
    
  2. 打开springboot日志

    # springboot默认的日志级别是info,feign的debug日志级别就不会输出
    logging:
      level:
        com.kiwi.order.feign: debug
    
  3. 全局配置
    使用@Configuration会作用到所有的服务提供方

  4. 局部配置

    • 配置类的方式

      如果只想针对某一个服务进行配置,就不要加@Configuration,然后再@FeignClient上用configuration属性指定FeignConfig

    @FeignClient(value = "product-service",path = "/product",configuration = FeignConfig.class)
    public interface ProductFeignService {
    
        @RequestMapping("/{id}")
        String get(@PathVariable("id") Integer id);
    
    }
    
    • yml的方式

    在调用方的yml配置文件中添加一下配置

    # Feign日志局部配置
    feign:
      client:
        config:
          stock-service:
            loggerLevel: BASIC
    

OpenFeign超时时间配置

说明:这里的超时时间在sentinel集成之后会交给sentinel来做。

  • 全局类配置
@Configuration
public class FeignConfig {

    @Bean
    public Request.Options options(){
        return new Request.Options(5000,10000);
    }

}
  • yml配置
feign:
  client:
    config:
      stock-service:# 对应
        # 日志级别
        loggerLevel: BASIC
        # 连接超时时间,默认2s
        ConnectTimeout: 5000
        # 请求处理时间,默认5s
        readTimeout: 10000

自定义OpenFeign拦截器

OpenFeign拦截器拦截的是服务调用方到服务提供方的,MVC的拦截器是拦截用户请求到服务端的。

  • 编写拦截器代码(实现RequestInterceptor接口)
public class CustomFeignInterceptor implements RequestInterceptor {

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

    public void apply(RequestTemplate requestTemplate) {
        //TODO: todo something~
        String uuid = String.valueOf(UUID.randomUUID());
        requestTemplate.header("uuid", uuid);
        logger.info("feign拦截器生效,uuid:" + uuid);
    }
}
  • 全局配置(配置类的方式)
@Configuration
public class FeignConfig {

    @Bean
    public CustomFeignInterceptor customFeignInterceptor(){
        return new CustomFeignInterceptor();
    }

}
  • yml配置方式
feign:
  client:
    config:
      product-service: # 可针对具体的服务进行配置
        requestInterceptors[0]: # 配置拦截器,可多个
          com.kiwi.order.intercptor.feign.CustomFeignInterceptor
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
12-18 155
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值