在SpringCloud的feign的调用过程中,我们可能需要传递token,header等数据,可以用feign的RequestInterceptor
拦截器去处理,直接撸代码吧。
package com.fk.mgmg.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* feign 统一token拦截器
*/
@Component
@Slf4j
public class FeignTokenInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
if(null == getHttpServletRequest() ) {
// throw new ServiceException("403", "noTokenRequestHeader");
log.error("noTokenRequestHeader");
return;
}
String userId = getHttpServletRequest().getHeader("userId");
// requestTemplate.header("userId", getHeaders(getHttpServletRequest()).get("userId"));
requestTemplate.header("userId", userId);
requestTemplate.header("token", getHeaders(getHttpServletRequest()).get("token"));
}
private HttpServletRequest getHttpServletRequest() {
try {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
} catch (Exception e) {
// e.printStackTrace();
return null;
}
}
/**
* Feign拦截器拦截请求获取Token对应的值
* @param request
* @return
*/
private Map<String, String> getHeaders(HttpServletRequest request) {
Map<String, String> map = new LinkedHashMap<>();
Enumeration<String> enumeration = request.getHeaderNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement();
String value = request.getHeader(key);
map.put(key, value);
}
return map;
}
}