前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >自定义拦截器(OpenFeign)

自定义拦截器(OpenFeign)

作者头像
问天丶天问
发布2024-01-20 10:18:35
1340
发布2024-01-20 10:18:35
举报
文章被收录于专栏:问天丶天问问天丶天问

拦截器代码

代码语言:javascript
复制
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);
    }
}

拦截器配置

配置类

代码语言:javascript
复制
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

代码语言:javascript
复制
# 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 字段
代码语言:javascript
复制
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
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2024-01-18,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 拦截器代码
  • 拦截器配置
    • 配置类
      • 配置文件 application.yml
      • 效果查看
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档