Feign远程调用参数里面内容丢失

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Feign远程调用参数里面内容丢失

杨林伟   2022-05-23 我要评论

Feign远程调用参数里面内容丢失

举个例子

服务A提供了如下接口(注意这里的参数url是一个地址):

@GetMapping("/getSample")
public String getSample(@RequestParam String url){
     //此处省略逻辑......
}

服务B需要调用服务A的接口,调用如下:

sampleFeignClient.getSample("http://www.xxx.com?name=dumas&age=18");

提出问题:此时调用服务A接口后,在A服务接收的方法体内,断点会发现后面的参数age=18会丢失。

问题的原因:Feign远程调用是使用HTTP协议的,可能是获取参数的时候,把参数url里面的内容当成了参数,所以直接舍弃了。

解决方法

服务B调用前,使用URLEncoder.encode(url,"UTF-8");

服务A获取参数后,使用URLDecoder.decode(url, "UTF-8");

Feign远程调用细节--丢失数据

同步调用

我这里只添加了header中的Cookie,当然也可以遍历header,把所有的都添加到新的请求,解决办法跟Gateway丢失请求头类似。

@Configuration
public class FeignConfiguration {
    //feign远程调用丢失请求头问题
    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String cookie = request.getHeader("Cookie");
            template.header("Cookie",cookie);
        };
    }
}

异步调用

当我们使用异步调用openfeign,上述代码就会报空指针,获取不到当前的请求。

我们先获取到当前请求,再分享给子线程。

RequestAttributes attributes = RequestContextHolder.getRequestAttributes();
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
    RequestContextHolder.setRequestAttributes(attributes);
    feign.doService();
}, executor);

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们