springcloud中微服务之间feign传参

Posted dyunfeng

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springcloud中微服务之间feign传参相关的知识,希望对你有一定的参考价值。

1、自定义类实现RequestInterceptor接口类:

@Component
public class FeignInterceptor implements RequestInterceptor{

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            template.header("user",request.getHeader("user"));
        }
    }
}

2、自定义Hystrix的默认隔离策略:网上很多代码例子

3、如果想要把参数通过HTTP请求的header传递到其他服务,就需要另外做些配置,首先你要把参数添加到header里面,然后就可以通过feign传递了,如下:

技术图片

 

 4、MutableHttpServletRequest是一个工具类:

public class MutableHttpServletRequest extends HttpServletRequestWrapper {
    // holds custom header and value mapping
    private final Map<String, String> customHeaders;

    public MutableHttpServletRequest(HttpServletRequest request){
        super(request);
        this.customHeaders = new HashMap<String, String>();
    }

    public void putHeader(String name, String value){
        this.customHeaders.put(name, value);
    }

    public String getHeader(String name) {
        // check the custom headers first
        String headerValue = customHeaders.get(name);

        if (headerValue != null){
            return headerValue;
        }
        // else return from into the original wrapped object
        return ((HttpServletRequest) getRequest()).getHeader(name);
    }

    public Enumeration<String> getHeaderNames() {
        // create a set of the custom header names
        Set<String> set = new HashSet<String>(customHeaders.keySet());

        // now add the headers from the wrapped request object
        @SuppressWarnings("unchecked")
        Enumeration<String> e = ((HttpServletRequest) getRequest()).getHeaderNames();
        while (e.hasMoreElements()) {
            // add the names of the request headers into the list
            String n = e.nextElement();
            set.add(n);
        }

        // create an enumeration from the set and return
        return Collections.enumeration(set);
    }
}

5、另一个服务在想用的地方接收参数:

HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
String userStr = request.getHeader("user");

 

以上是关于springcloud中微服务之间feign传参的主要内容,如果未能解决你的问题,请参考以下文章

解决:SpringCloud中Feign支持GET请求POJO传参

springcloud学习2:使用feign进行微服务之间的调用

springcloud学习2:使用feign进行微服务之间的调用

spring cloud中微服务之间的调用以及eureka的自我保护机制

SpringCloud系列——Feign 服务调用

SpringCloud-服务之间如何进行调用(OpenFeign)