springcloud中微服务之间feign传参

2021-01-05 13:28

阅读:595

标签: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 customHeaders;

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

    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 getHeaderNames() {
        // create a set of the custom header names
        Set set = new HashSet(customHeaders.keySet());

        // now add the headers from the wrapped request object
        @SuppressWarnings("unchecked")
        Enumeration 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


评论


亲,登录后才可以留言!