0

我想使用 @FeignClient 根据运行的环境从属性中获取 URL。 喜欢:我有testdevprod。所有这些环境都有不同的 URL,例如: test: http://localhost:9000 dev : http://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"

可以吗?如果可以;如何?

4

1 回答 1

0

是的,做一个工厂。

编辑:Class<T> 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);
    }
}
于 2019-09-24T09:34:18.063 回答