通过OpenFeign远程调用同局域网的其他接口
Posted msy-2000
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了通过OpenFeign远程调用同局域网的其他接口相关的知识,希望对你有一定的参考价值。
通过OpenFeign远程调用同局域网的其他接口
需要的依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-- feign httpclient -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
项目结构
关于Client的编写
@Repository
@FeignClient(contextId = "PayClient", value = "ruoyi-pay",url = "192.168.31.47:9206")
public interface PayClient
@GetMapping("/pay/chargeable/list?pageNum=1&pageSize=10")
TableDataInfo list(@RequestBody PayChargeable payChargeable);
拦截器的编写
@Component
public class FeignInterceptor implements RequestInterceptor
@Override
public void apply(RequestTemplate requestTemplate)
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if(requestAttributes != null)
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String authorization = request.getHeader("Access-Control-Allow-Origin");
requestTemplate.header("Access-Control-Allow-Origin", "*");
作用: 将token放入请求头中
编写Controller
先将Client自动注入
openFeign远程调用丢失请求头
微服务调用的时候请求不会传递参数.比如调用方服务请求头中有cookie存放sessionId,而被调用方服务没有请求头,从而没有cookie信息,也就不能根据cookie中存放的sessionId获取session信息,影响后续操作.
解决办法
通过实现RequestInterceptor接口,完成对所有的Feign请求,传递请求头和请求参数。本质是通过ThreadLocal线程共享变量实现.
import feign.RequestInterceptor; import feign.RequestTemplate; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; @Configuration public class FeignConfig { /** * 解决feign远程调用丢失请求头的问题 * @return */ @Bean public RequestInterceptor requestInterceptor(){ return new RequestInterceptor(){ @Override public void apply(RequestTemplate requestTemplate) { //老请求 获取老请求的cookie信息 ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (requestAttributes != null){ String cookie = requestAttributes.getRequest().getHeader("Cookie"); //同步到新请求中 requestTemplate.header("Cookie",cookie); } } }; } }
以上是关于通过OpenFeign远程调用同局域网的其他接口的主要内容,如果未能解决你的问题,请参考以下文章
干掉OpenFeign,SpringBoot 3.0 自带的 HTTP 客户端真香!