具有不同拦截器的多个 Fe​​ign 客户端

Bri*_*ian 5 java spring-boot feign

在 Spring Boot 中有两个 Feign 客户端做不同的事情,但希望对它们进行不同的身份验证。

@FeignClient(
    name = "...",
    url = "${url1}",
    configuration = Config1.class
)
public interface Client1 {
    @PostMapping(
        path = "...",
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    JsonNode doThing(@RequestBody JsonNode thing);
}

@FeignClient(
    name = "...",
    url = "${url2}",
    configuration = Config2.class
)
public interface Client2 {
    @PostMapping(
        path = "...",
        consumes = MediaType.APPLICATION_JSON_VALUE,
        produces = MediaType.APPLICATION_JSON_VALUE)
    JsonNode doThing(@RequestBody JsonNode thing);
}
Run Code Online (Sandbox Code Playgroud)

它们都需要基本身份验证,但用户名和密码的值不同。为此,我考虑使用单独的Config类来设置各自的客户端:

@Configuration
public class Client1 {
    private final String user;
    private final String password;

    public Client1(final Config1 config) {
        this.user = config.getUser();
        this.password = config.getPassword();
    }

    @Bean(name = "client1")
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(user, password);
    }
}

@Configuration
public class Client2 {
    private final String user;
    private final String password;

    public Client1(final Config2 config) {
        this.user = config.getUser();
        this.password = config.getPassword();
    }

    @Bean(name = "client2")
    public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
        return new BasicAuthRequestInterceptor(user, password);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我的 API 返回 HTTP 4xx 错误,就好像拦截器根本不起作用一样。我可以获得一些有关正确设置的指导吗?

(请注意,我给出了这些 beans name,因为否则它们会与 DI 发生冲突。)

小智 4

我想你必须消除刻板印象@Configuration

我实际上是在搜索类似问题时来到这里的。我确实有(和你一样)两个不同的配置。一个 FeignClient 有身份验证,第二个客户端没有身份验证。但是第二个客户端正在使用两个 RequestInterceptor (我实现了一个 noop-RequestInterceptor 只是为了日志记录)。

你真的能解决你的问题吗?