自定义拦截器(OpenFeign)

拦截器代码

package com.learning.springcloud.order.feign;

import feign.RequestInterceptor;
import feign.RequestTemplate;

import java.util.UUID;

public class CustomFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // eg: 统一自定义请求信息信息    
        String customHeaderInfo = UUID.randomUUID().toString();    
        requestTemplate.header("custom_header_info", customHeaderInfo);
    }
}

拦截器配置

配置类

package com.learning.springcloud.order.feign.config;

import com.learning.springcloud.order.feign.FeignAuthRequestInterceptor;
import feign.Logger;
import feign.Request;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Configuration 作用域为所有的服务提供方  全局配置
 * 局部配置: FeignClient configuration的值
 */
@Configuration
public class FeignConfig {


    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

//   修改契约为 Feign默认注解方式
//    @Bean
//    public Contract feignContract(){
//        return  new Contract.Default();
//    }

    @Bean
    public Request.Options options() {
        // 第一个 连接超时  第二个 读取超时
        return new Request.Options(5000, 10000);
    }

    /**
     * 自定义请求拦截器
     *
     * @return
     */
    @Bean
    public CustomFeignInterceptor customFeignInterceptor() {
        return new CustomFeignInterceptor();
    }

}

配置文件 application.yml

# springboot 默认日志级别是info  因此 feign的debug日志级别就不会输出
logging:
  level:
    com.learning.springcloud.order.feign: debug

# 局部日志配置
feign:
  client:
    config:
      product-service: # 服务名称
        logger-level: BASIC  # 基础日志
#        contract: feign.Contract.Default # 指定Feign原生注解契约配置
        connect-timeout: 5000
        read-timeout: 10000
      stock-service:
        request-interceptors:
          - com.learning.springcloud.order.feign.CustomFeignInterceptor

效果查看

  • 全量的调用日志中可以查看到自定义拦截器增加的 custom_header_info 字段

2024-01-14 17:47:21.138 DEBUG 11076 --- [nio-8040-exec-1] c.l.s.order.feign.StockFeignService      : [StockFeignService#reductStock] ---> GET http://stock-service/stock/reduct HTTP/1.1
2024-01-14 17:47:21.138 DEBUG 11076 --- [nio-8040-exec-1] c.l.s.order.feign.StockFeignService      : [StockFeignService#reductStock] custom_header_info: bf8bd0a9-d7b6-446b-937c-7314610a3895

  • 18
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

菜逼の世界

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值