拦截器代码
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 字段文章来源地址https://www.toymoban.com/news/detail-802865.html
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
文章来源:https://www.toymoban.com/news/detail-802865.html
到了这里,关于自定义拦截器(OpenFeign)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!