【问题标题】:How to Set Request Headers Using a Feign Client?如何使用 Feign 客户端设置请求标头?
【发布时间】:2016-09-14 08:25:41
【问题描述】:

我们正在使用 Spring Cloud 框架开发一套微服务,我们需要做的事情之一就是设置请求标头。我知道我可以将参数 @RequestHeader 传递给 Feign 方法,但该值需要来自另一个 bean。我不知道 SPEL 是否可以用于 Feign 参数值。 我在想这对于大多数客户来说是一个足够常见的用例,所以会有一些例子,但到目前为止我还没有找到任何例子。当然,我可以深入研究 Spring 课程代码并尝试覆盖默认的 Feign 配置,但如果我必须编写大量代码来实现这一点,它就有点违背了声明式客户端的目的。 有什么想法吗?

【问题讨论】:

    标签: spring-mvc spring-cloud microservices netflix-feign spring-cloud-netflix


    【解决方案1】:

    我在使用 RequestInterceptor 之前已经这样做了,如下所示:

    @Component
    public class MyRequestInterceptor implements RequestInterceptor {
      @Override
      public void apply(RequestTemplate template) {
        template.headers(getHeadersFromWherever());
      }
    }
    

    您可以在这里找到更多有用的信息:

    https://github.com/Netflix/feign#user-content-setting-headers-per-target

    【讨论】:

    • 你把这个放在哪里? Spring Cloud doc 声明有一个 FeignClientsConfiguration 和一个 FooConfiguration@FeignClient(name = "stores", configuration = FooConfiguration.class) public interface StoreClient {...}
    • 你可以把它放在你的@ComponentScan中的任何地方
    • 如果你将它包含在@ComponentScan 中,拦截器将应用于所有的 Feign 客户端。另一方面,如果在FooConfiguration.class 中定义,它将仅应用于特定的 FeignClient。
    猜你喜欢
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2020-01-08
    • 2017-03-08
    相关资源
    最近更新 更多