在SpringCloud的feign的調(diào)用過程中违帆,我們可能需要傳遞token,header等數(shù)據(jù)金蜀,可以用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 統(tǒng)一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攔截器攔截請(qǐng)求獲取Token對(duì)應(yīng)的值
* @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;
}
}