感兴趣的话大家可以关注一下公众号 : 猿人刘先生 , 欢迎大家一起学习 , 一起进步 , 一起来交流吧!
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();
}
}
我在工程中是这样使用的