【问题标题】:Can I configure a @FeignClient url using a properties/yml file with custom property name?我可以使用带有自定义属性名称的属性/yml 文件配置@FeignClient url吗?
【发布时间】:2020-01-24 08:40:51
【问题描述】:

我想使用 @FeignClient 根据运行的环境从属性中获取 URL。 :我有testdevprod。所有这些环境对于 example 都有不同的 URL: testhttp://localhost:9000 devhttp://localhost:8080 prod : http://localhost:8181

@FeignClient(name = "my-test-servies", url = "${com.test.my.access.url}")
@RequestMapping(method = RequestMethod.GET, value = "/authors")
public interface MyFeignClient {
  public List<Author> getAuthors();
}

这可行,但我希望根据环境更改 URL 属性。当我使用单个属性文件时,我的 yml 属性文件如下:application.yml

com:
  prod:
    my:
      access:
        url: "http://localhost:8181"
  test:
    my:
      access:
        url: "http://localhost:9000"
  dev:
    my:
      access:
        url: "http://localhost:8080"

可以吗?如果可以;怎么样?

【问题讨论】:

  • 使用配置文件并删除属性中对 env 的显式调用?
  • 配置文件仅用于此目的。您希望在单个文件中拥有所有属性的任何具体原因?
  • 是的,我在我的其他服务中使用配置文件,但我想在我的服务中使用单个 yml/property 文件。

标签: java spring spring-boot openfeign


【解决方案1】:

是的,做一个工厂。

编辑:Class&lt;T&gt; clazz 是一个 Feign 接口。

public class FeignClientFactory {

    public static <T> T build(final String url, Class<T> clazz) {
        return Feign.builder().client(new OkHttpClient()).logger(new Slf4jLogger(clazz)).logLevel(Logger.Level.FULL)
                .encoder(new JacksonEncoder()).decoder(new JacksonDecoder()).target(clazz, url);
    }

    public static <T> T build(final String url, Class<T> clazz, ObjectMapper mapper) {
        Assert.notNull(mapper, "The mapper can't be null !");

        return Feign.builder().client(new OkHttpClient()).logger(new Slf4jLogger(clazz)).logLevel(Logger.Level.FULL)
                .encoder(new JacksonEncoder(mapper)).decoder(new JacksonDecoder(mapper)).target(clazz, url);
    }

    public static <T> T buildWithInterceptor(final String url, Class<T> clazz, RequestInterceptor interceptor) {
        return Feign.builder().client(new OkHttpClient()).logger(new Slf4jLogger(clazz)).logLevel(Logger.Level.FULL)
                .encoder(new JacksonEncoder()).requestInterceptor(interceptor).decoder(new JacksonDecoder())
                .target(clazz, url);
    }
}

【讨论】:

  • 你有任何示例链接可以参考吗?
猜你喜欢
  • 2015-05-30
  • 2017-08-28
  • 1970-01-01
  • 2010-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-13
相关资源
最近更新 更多