场景:服务A 调用 服务B
1 编写拦载器类
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;public class Interceptor_a implements RequestInterceptor {@Overridepublic void apply(RequestTemplate template) {System.err.println("拦截器");ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();template.header("code",request.getHeader("code"));}
}
2 使用拦截器,两种方法,选一种即可
//方法1
@FeignClient(value= "app_b",path = "/dts_address",configuration = Interceptor_a.class
)
#方法2
feign:sentinel:enabled: trueclient:config:app_b:# 配置拦截器request-interceptors:- org.example.Interceptor_adefault:logger-level: fullconnect-timeout: 10000read-timeout: 10000
logging:level:cn.haiwang: debug
3 测试,服务A发请示时,在header中设置参数code,服务B可以拿到拦截器里设置的信息
/*
服务b 工程的代码
*/
@RequestMapping(value="/add")public Object add(@RequestBody DtsAddress dtsAddress){ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = attributes.getRequest();Enumeration<String> headerNames = request.getHeaderNames();while (headerNames.hasMoreElements()){String s = headerNames.nextElement();String header = request.getHeader(s);System.err.println(s+" : "+header);}}