Feign局部配置

本文介绍了如何在SpringBoot项目中使用Feign进行局部配置,避免全局设置。通过`FeignRequestInterceptor`和`FeignRequestConfig`类,实现在调用特定服务时自动添加token和appKey请求头,确保请求的灵活性和安全性。
摘要由CSDN通过智能技术生成

环境:

SpringBoot版本: 2.1.13.RELEASE

项目中遇到请求某个服务时需要带上特定的token和appKey, 但是请求其他服务不需要带. 所以需要使用到Feign局部配置功能.

代码如下:

/**
 * 类FeignRequestInterceptor.java的实现描述:增加请求头,需要根据包配置
 * 
 * @author dorra 2022/7/7 9:19:19
 */
//@Configuration  此处不能加@Configuration,加了就是全局配置
public class FeignRequestInterceptor implements RequestInterceptor {

	private static final String datahouse_auth_name = "appKey";
	private static final String default_appKey = "XXX";

	@Value("${feignRequest.appKey}")
	private String appKey;

	/*
	 * 设置请求头
	 * 
	 * @see feign.RequestInterceptor#apply(feign.RequestTemplate)
	 */
	@Override
	public void apply(RequestTemplate template) {
		if (StringUtils.isBlank(appKey)) {
			appKey = default_appKey;
		}
		template.header(datahouse_auth_name, appKey);
	}

}

 注意: 不能加@Configuration,加了就是全局配置

/**
 * 增加请求头,需要根据包配置,需要请在@FeignClient加上属性: configuration = FeignRequestConfig.class
 * @author dorra
 * @date 2022/8/10 11:12
 */
//此处不能加@Configuration,加了就是全局配置
public class FeignRequestConfig {

    @Bean
    public FeignRequestInterceptor feignRequestInterceptor() {
        return new FeignRequestInterceptor();
    }
}

注意: 不能加@Configuration,加了就是全局配置

使用:

@FeignClient(name = "data-server", url = "${dataserver}", configuration = FeignRequestConfig.class)
public interface DataServer {

}

 

参考文章:

Feign全局配置和局部配置_shadon178的博客-CSDN博客_feign全局配置

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值