码迷,mamicode.com
首页 > 编程语言 > 详细

springcloud中微服务之间feign传参

时间:2020-05-28 16:41:25      阅读:108      评论:0      收藏:0      [点我收藏+]

标签:super   info   tor   void   ati   this   inter   hystrix   eth   

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传参

标签:super   info   tor   void   ati   this   inter   hystrix   eth   

原文地址:https://www.cnblogs.com/dyunfeng/p/12981279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!