Feign拦截器:RequestInterceptor
文章目录RequestInterceptor概述自定义拦截器RequestInterceptor概述Feign支持请求拦截器,在发送请求前,对发送的模板进行操作,例如设置请求头等属性。public interface RequestInterceptor {/*** 每个请求都会调用apply方法*/void apply(RequestTemplate template);}自定义拦截器自定义拦截
·
RequestInterceptor概述
Feign支持请求拦截器,在发送请求前,对发送的模板进行操作,例如设置请求头等属性。
public interface RequestInterceptor {
/**
* 每个请求都会调用apply方法
*/
void apply(RequestTemplate template);
}
自定义拦截器
自定义拦截器
@Configuration
@Slf4j
public class FeignClientInterceptorConfig implements RequestInterceptor {
@Override
public void apply(RequestTemplate requestTemplate) {
log.info("feign interceptor entered");
// 设置请求头信息
requestTemplate.header("authKey","myKeyInfo");
}
}
配置到FeignClient
@Component
// 服务提供者名称
@FeignClient(value = "cloud-provider-service", configuration = {FeignClientInterceptorConfig.class, FeignConfig.class})
public interface RemoteUserService {
@RequestMapping("/user/search/v1") // 要调用的接口
RestResult<List<UserTest>> searchUser(@RequestBody UserTest userTest);
}
服务提供端获取请求头
@ApiOperation(value = "查询用户")
@PostMapping(value = "/search/v1")
public RestResult<List<UserTest>> search(@RequestBody UserTest userTest, HttpServletRequest request) {
try {
String authKey = request.getHeader("authKey");
log.info("自定义Header值 authKey:[{}]",authKey);
List<UserTest> userTests = userTestService.selectList(userTest);
log.info("查询成功:端口号:{}", serverPort);
return RestResult.success(userTests, ResultCode.SUCCESS);
} catch (Exception e) {
return RestResult.fail(ResultCode.DATA_ACCESS_ERROR);
}
}
消费端测试
@RestController
@Api(tags = "消费端")
public class ConsumerController {
@Autowired
private RemoteUserService remoteUserService;
@ApiOperation(value="查询用户")
@PostMapping(value = "/search/v2")
public RestResult<List<UserTest>> searchUser(@RequestBody UserTest userTest) {
try {
RestResult<List<UserTest>> listRestResult = remoteUserService.searchUser(userTest);
return listRestResult;
} catch (Exception e) {
return RestResult.fail(ResultCode.DATA_ACCESS_ERROR);
}
}
}
调用接口:http://localhost/search/v2
服务端成功获取到自己设置的Header
请求信息
更多推荐
已为社区贡献3条内容
所有评论(0)