2

Micronaut supports retry mechanism for http clients if we use it in a declarative client like this :

@Client("http://127.0.0.1:8200")
@Retryable(delay = "${retry-delay}", attempts = "${retry-attempts}")
@Header(name = "username", value = "password")

public interface SampleHttpClient {
    @Get(value = "/v1/kv/data/", produces = MediaType.APPLICATION_JSON)
    HttpResponse<String> getVaultSecret();
}

Here retry-delay and retry-attempts are read from configuration yaml file.

But I am creating the http clients in my code on the fly as show below. This is because I get the http client parameters(URL, retry properties, header etc) at runtime.

How can I add retry option to my http configuration here ?

HttpClient client = null;
var configuration = new ServiceHttpClientConfiguration("myId", null, 
                                  null, new DefaultHttpClientConfiguration());  
   
// how to add retry to http configuration here ???       

client = new DefaultHttpClient("http://127.0.0.1:8200", configuration);

var uri = UriBuilder.of("http://127.0.0.1:8200").path("/v1/kv/data/").build();
var request = HttpRequest.GET(uri).header("username","password");
var response = client.toBlocking().exchange(request);
shashank
  • 65
  • 6

1 Answers1

1

Basically in the background micronaut uses the AOP Advice for retrying using @Retryable annotation

So, you can basically move the logic into method and implement the logic to retry that method on exception and with delay.

@Retryable(attempts = "2", includes =[NullPointerException.class,..], delay= "1s")
public void clientCall() {

  client = new DefaultHttpClient("http://127.0.0.1:8200", configuration);

  var uri = UriBuilder.of("http://127.0.0.1:8200").path("/v1/kv/data/").build();
  var request = HttpRequest.GET(uri).header("username","password");
  var response = client.toBlocking().exchange(request);
}

You can also configure the values in application.yml/application.properties and use them in annotation

@Retryable(
attempts = "\${micronaut.http.services.get_core_item_graphql.retryAttempts}",
delay = "\${micronaut.http.services.get_core_item_graphql.retryDelay}")
Ryuzaki L
  • 37,302
  • 12
  • 68
  • 98
  • Again the value of attempts is hardcoded. Here I should be able to set the value to attempts through java code. – shashank Mar 29 '23 at 11:44
  • you can configure them in properties file @shashank – Ryuzaki L Mar 29 '23 at 11:55
  • In my case, they cannot be read from config file, I should read it from db and modify them at runtime. So I am looking at reflection APIs to change the value of annotation at runtime – shashank Mar 29 '23 at 12:03
  • "So I am looking at reflection APIs to change the value of annotation at runtime" - I don't expect that to work. An approach that would work is using `@Retryable` and configuring a property source that reads config from the db. – Jeff Scott Brown Apr 03 '23 at 16:55