服务之间需要传递参数、请求头等,可以通过 RequestTemplate 对象进行传递,代码如下:
1、配置 request 拦截器类
package com.xxx.feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
/**
* <p>ClassName: FeignConfigure</p>
* <p>Description: feign对request做拦截处理</p>
* <p>Author: xxx</p>
* <p>Date: xxx</p>
*/
@Configuration
public class FeignConfigure implements RequestInterceptor {
/**
* <p> 在此可以做request参数处理,例如添加头部参数等 </p>
* @author: xxx
* @date: xxx
* @param requestTemplate :
**/
@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 value = request.getHeader(name);
requestTemplate.header(name, value);
}
}
}
}
2、配置好 RequestTemplate 拦截器之后,需要在 FeignClinent 接口类中引用拦截器:
@FeignClient(value = "xxx-service",configuration = FeignConfigure.class)
@FeignClient(value = "xxx-service",configuration = FeignConfigure.class)
// 示例通过网关调用,第一个"/xxx"是 xx-service 网关应用访问的根目录(即路由转发之前的断言匹配规则)
// 第二个"/xxx"是被调用服务方的 @RequestMapping 路径
@RequestMapping(value = {"/xxx/xxx"})
public interface VhclFeignClient {
@GetMapping(value = "/getVchlInfoById")
CommonResult<Vhcl> getVchlInfoById(@RequestParam("id") int id);
@PostMapping("/uc/saveVchlInfo")
CommonResult<Vhcl> saveVchlInfo(Vhcl vhcl);
}
网友评论