项目中经常涉及内部模块之间的相互调用,导致在用A模块调用B模块的方法时,请求头里面的token信息传递不到B模块,从而获取不到用户信息,导致保存数据时,保存的数据不全,根据网上一些博客写此篇博客以作记录,代码中如有错漏之处,请各位大神海涵!
(下面的操作步骤没关系,只要有就可以)
1.Configuration代码
package com.xxx.demo;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* @description: Feign内部调用时带上请求头信息
* @author: xxx
* @create: 2019-08-09 10:02
* 注意:要去yml里面改变hystrix Feign的隔离策为strategy: SEMAPHORE
**/
@Configuration
public class FeignConfiguration implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
template.header(name, values);
}
}
Enumeration<String> bodyNames = request.getParameterNames();
StringBuffer body =new StringBuffer();
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);
template.body(body.toString());
}
}
}
2.yml配置
feign:
hystrix:
enabled: true
client:
config:
default:
connectTimeout: 60000
readTimeout: 60000
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
strategy: SEMAPHORE
thread:
timeoutInMilliseconds: 60000
3.Feignclient调用的时候指定configuration
package com.xxx.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.util.Map;
@FeignClient(name = "device", configuration = FeignConfiguration.class)
public interface MonitorNetService {
@RequestMapping(value = "api/monitorNetImport", method = RequestMethod.POST)
public Map<String, Object> monitorNetImport(@RequestBody Map<String, String> params);
}
本文介绍了解决Feign内部模块调用时Token信息丢失的问题,通过配置FeignConfiguration类,确保请求头信息在跨模块调用时能够完整传递,避免了因Token缺失导致的数据保存不全问题。
1184

被折叠的 条评论
为什么被折叠?



