Home > Software design >  Get Spring Default Feign Options on programmatically created feign client
Get Spring Default Feign Options on programmatically created feign client

Time:03-01

I am trying to get the default feign options/config to use it in feign clients that I create programatically using Feign.Builder:

This is the config (application.yaml) that I want to get:

feign:
  client:
    config:
      default:
        connect-timeout: 5000
        read-timeout: 5000

What I tried to do is to do is to add @EnableFeignClients and try to get the FactoryBean<Request.Options> or it's implementation OptionsFactoryBean but I don't see it being injected by Spring anywhere.

I've also tried searching in StackOverflow and other websites to see if there are other people that have tried what I am trying to do, but I wasn't able to find any information hence why I am creating this question.

public MyClientFactory(Client client,
                       ObjectMapper objectMapper,
                       FactoryBean<Request.Options> optionsFactory,
                       ErrorDecoder errorDecoder) throws Exception {
    this.builder = Feign.builder()
            .client(client)
            .decoder(new JacksonDecoder(objectMapper))
            .encoder(new JacksonEncoder(objectMapper))
            .options(optionsFactory.getObject())
            .errorDecoder(errorDecoder);
}

Can someone please let me know how I can get the default spring feign configs? Maybe my approach is incorrect?

Thanks!

CodePudding user response:

Haven't tried it but I assume you'll need a bean from the FeignClientProperties class.

CodePudding user response:

I ended up creating a Request.Options @Bean based on FeignClientProperties as @Arnold Galovics suggested.

@Bean
Request.Options options(FeignClientProperties feignClientProperties) {
    FeignClientProperties.FeignClientConfiguration feignClientConfiguration = feignClientProperties.getConfig().get(feignClientProperties.getDefaultConfig());

    Request.Options defaultOptions = new Request.Options();
    return new Request.Options(
            Optional.ofNullable(feignClientConfiguration.getConnectTimeout()).orElse(defaultOptions.connectTimeoutMillis()), TimeUnit.MILLISECONDS,
            Optional.ofNullable(feignClientConfiguration.getReadTimeout()).orElse(defaultOptions.readTimeoutMillis()), TimeUnit.MILLISECONDS,
            Optional.ofNullable(feignClientConfiguration.isFollowRedirects()).orElse(false)
    );
}

And then I injected this bean in my Feign Client Factory:

public MyClientFactory(Client client,
                       ObjectMapper objectMapper,
                       Request.Options options,
                       ErrorDecoder errorDecoder) {
    this.builder = Feign.builder()
            .client(client)
            .decoder(new JacksonDecoder(objectMapper))
            .encoder(new JacksonEncoder(objectMapper))
            .options(options)
            .errorDecoder(errorDecoder);
}
  • Related