SpringCloud OpenFeign远程调用传递请求头信息方式
更新时间:2026年03月19日 08:45:48 作者:lingering fear
这篇文章主要介绍了SpringCloud OpenFeign远程调用传递请求头信息方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
1.实现RequestInterceptor接口
package com.liuxs.common.core.config;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Assert;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* @author: Liu Yuehui
* @ClassName: RequestInterceptor
* @date: 2022/12/16 19:01
* @description: Feign请求拦截器(设置请求头,传递登录信息)
**/
@Slf4j
public class FeignBasicAuthRequestInterceptor implements RequestInterceptor{
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
Assert.notNull(attributes , "FeignBasicAuthRequestInterceptor apply() attributes is null");
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
requestTemplate.header(name, values);
}
}
Enumeration<String> bodyNames = request.getParameterNames();
StringBuilder body = new StringBuilder();
if (bodyNames != null) {
while (bodyNames.hasMoreElements()) {
String name = bodyNames.nextElement();
String values = request.getParameter(name);
body.append(name).append("=").append(values).append("&");
}
}
if(body.length() != 0) {
body.deleteCharAt(body.length()-1);
requestTemplate.body(body.toString());
log.info("feign interceptor body:{}" , body.toString());
}
}
}
2.注册配置
package com.liuxs.gateway.config;
import com.liuxs.common.core.config.FeignBasicAuthRequestInterceptor;
import feign.RequestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author: Liu Yuehui
* @ClassName: FeignSupportConfig
* @date: 2022/12/16 19:21
* @description: Feign配置注册(全局)
**/
@Configuration
public class FeignSupportConfig {
@Bean
public RequestInterceptor requestInterceptor() {
return new FeignBasicAuthRequestInterceptor();
}
}
我在工程中是这样使用的:


总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
详解Spring Security的formLogin登录认证模式
对于一个完整的应用系统,与登录验证相关的页面都是高度定制化的,非常美观而且提供多种登录方式。这就需要Spring Security支持我们自己定制登录页面,也就是本文给大家介绍的formLogin模式登录认证模式,感兴趣的朋友跟随小编一起看看吧2019-11-11
IDEA源码修改器JarEditor使用(反编译-打包一步到位)
JarEditor是一个IDEA插件,用于修改jar包中的类文件,它允许用户在不解压jar包的情况下,直接在IDEA中编辑和修改类文件的源码,修改完成后,可以一键编译并生成新的jar包,替换原jar包2025-01-01
java中Memcached的使用实例(包括与Spring整合)
这篇文章主要介绍了java中Memcached的使用实例(包括与Spring整合),具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-07-07


最新评论