如何使用feign实现拦截器(RequestInterceptor)实现request转发呢?
下文笔者通过示例的方式讲述request拦截器的示例分享
Feign支持定义一个拦截器 在请求前,进行相应的拦截 然后设置相应的请求头 实现思路: 只需实现RequestInterceptor接口 然后实现其apply方法即可例:
import com.java265.common.util.constant.HttpHeader; 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; @Slf4j @Component public class FeignAddHeaderRequestInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate template) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); if (attributes != null) { HttpServletRequest request = attributes.getRequest(); Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); if (name.startsWith(HttpHeader.HTTP_HEADER_PREFIX) || name.startsWith(HttpHeader.HTTP_HEADER_PREFIX.toLowerCase())) { String values = request.getHeader(name); template.header(name, values); } } } }else{ template.header("error", "888"); } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。