在运行时更改 FeignClient URL



具有假装客户端:

@FeignClient(name = "storeClient", url = "${feign.url}")
public interface StoreClient {
//..
}

是否可以利用环境更改的 Spring Cloud 功能在运行时更改 Feign url?(更改feign.url属性并调用/refresh终结点)

作为一种可能的解决方案 - 可以引入RequestInterceptor以便从RefreshScope中定义的属性RequestTemplate中设置 URL。

要实现此方法,应执行以下操作:

  1. RefreshScope中定义ConfigurationPropertiesComponent

    @Component
    @RefreshScope
    @ConfigurationProperties("storeclient")
    public class StoreClientProperties {
    private String url;
    ...
    }
    
  2. application.yml中指定客户端的默认 URL

    storeclient
    url: https://someurl
    
  3. 定义将切换 URL 的RequestInterceptor

    @Configuration
    public class StoreClientConfiguration {
    @Autowired
    private StoreClientProperties storeClientProperties;
    @Bean
    public RequestInterceptor urlInterceptor() {
    return template -> template.insert(0, storeClientProperties.getUrl());
    }
    }
    
  4. 在 URL 的FeignClient定义中使用一些占位符,因为它不会被使用

    @FeignClient(name = "storeClient", url = "NOT_USED")
    public interface StoreClient {
    //..
    }
    

现在,可以刷新storeclient.url,并且定义的URL将用于RequestTemplate发送的http请求。

一个扩展的答案,RequestInterceptor

  1. application.yml
app:
api-url: http://external.system/messages
callback-url: http://localhost:8085/callback
  1. @ConfigurationProperties
@Component
@RefreshScope
@ConfigurationProperties("app")
public class AppProperties {
private String apiUrl;
private String callbackUrl;
...
}
  1. @FeignClient-s 配置

确保您的...ClientConfig类没有注释任何@Component/...注释或由组件扫描找到。

public class ApiClientConfig {
@Bean
public RequestInterceptor requestInterceptor(AppProperties appProperties) {
return requestTemplate -> requestTemplate.target(appProperties.getApiUrl());
}
}
public class CallbackClientConfig {
@Bean
public RequestInterceptor requestInterceptor(AppProperties appProperties) {
return requestTemplate -> requestTemplate.target(appProperties.getCallbackUrl());
}
}
  1. @FeignClient-s
@FeignClient(name = "apiClient", url = "NOT_USED", configuration = ApiClientConfig.class)
public interface ApiClient {
...
}
@FeignClient(name = "callbackClient", url = "NOT_USED", configuration = CallbackClientConfig.class)
public interface CallbackClient {
...
}

相关内容

  • 没有找到相关文章

最新更新