欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

微服务通过feign调用时,跨服务间调用传递header

程序员文章站 2024-02-04 21:07:16
...

首先需要实现一个拦截器进行封装:

@Component
public class HystrixRequestWrapInterceptor implements HandlerInterceptor {
	
	public static final HystrixRequestVariableDefault<HttpServletRequest> REQUEST = new HystrixRequestVariableDefault<>();
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 在当前线程初始化HystrixRequestContext, 并设置请求头
		if (!HystrixRequestContext.isCurrentThreadInitialized()) {
		    HystrixRequestContext.initializeContext();
		}
		REQUEST.set(request);
		
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// do nothing
	}

// 销毁当前线程
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	    if (HystrixRequestContext.isCurrentThreadInitialized()) {
	        HystrixRequestContext.getContextForCurrentThread().shutdown();
	    }
	}

}

而后在feign注册配置中实现一个全局的RequestInterceptor

@Configuration
public class FeginConfig {
	
	@Bean
	public RequestInterceptor requestInterceptor(){
	    return template -> {
	    	
	    	
	    	if (!HystrixRequestContext.isCurrentThreadInitialized()) {
	    	    HystrixRequestContext.initializeContext();
	    	}
	    	HttpServletRequest request = HystrixRequestWrapInterceptor.REQUEST.get();
			
			
			if(null == request) {
				return;
			}
			
			// 获取RequestTemplate中已包含的请求头
			Map<String, Collection<String>> curHeaders = template.headers();
			Set<String> curHeaderNames = null==curHeaders?new HashSet<>():curHeaders.keySet()
					.stream().map(String::toLowerCase).collect(Collectors.toSet());
	    	
	        Enumeration<String> headerNames = request.getHeaderNames();
	        if (headerNames != null) {
	          while (headerNames.hasMoreElements()) {
	            String name = headerNames.nextElement();
	            // 如果RequestTemplate头信息中已经包含了该请求头, 跳过
	            if(curHeaderNames.contains(name)) continue;
	            
	            String values = request.getHeader(name);
	            template.header(name, values);
	          }
	        }
	    };
	}
    
	
    @Bean
    public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
    }

}
相关标签: spring cloud header