【SpringBoot】通过Feign调用传递Header中参数
如何通过Feign传递Header参数
问题描述
我们在SpringCloud中使用Feign请求另一个服务的Api接口时,有将Header中参数传递下去的需求,如果不做特殊处理,就会将Header中的参数丢失。
解决方案
方案一:通过 @RequestHeader(name = "headerName") 来传递
例如:Feign定义如下
@FeignClient(name = "service-name")
public interface XXXFeignClient {
@RequestMapping(value = "/user/getUserTicket", method = RequestMethod.GET)
String getUserTicket(@RequestParam("id") String id);
}
假设在服务service-name中的/user/getUserTicket接口需要从Header中取Referer数据,那么我们可以将上面代码进行改造:
@FeignClient(name = "service-name")
public interface XXXFeignClient {
@RequestMapping(value = "/user/getUserTicket", method = RequestMethod.GET)
String getUserTicket(@RequestParam("id") String id, @RequestHeader(name = "Referer") String referer);
}
然后在调用的时候将referer参数传递进去即可,如
public String getTicketById(@RequestParam("id") String id, HttpServletRequest request) {
String referer = request.getHeader("Referer");
return xxxFeignClient.getUserTicket(id, referer);
}
方案二:通过实现 RequestInterceptor 接口
首先,自定义实现RequestInterceptor接口的apply方法,如下
import org.springframework.stereotype.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
@Configuration
public class FeignConfiguration implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
Enumeration<String> headerNames = request.getHeaderNames();
if (headerNames != null) {
while (headerNames.hasMoreElements()) {
String name = headerNames.nextElement();
String values = request.getHeader(name);
requestTemplate.header(name, values);
}
}
}
}
然后将自定义的配置类配置到Feign中,就可以实现该Feign中接口Header参数的传递
@FeignClient(value = "service-name" ,configuration = FeignConfiguration.class)
public interface XXXFeignClient {
}
到此这篇关于SpringBoot 通过Feign调用传递Header中参数的文章就介绍到这了,更多相关SpringBoot Feign调用传递Header参数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!