Micronaut 支持 http 客户端的重试机制,如果我们在这样的声明式客户端中使用它:
@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();
}
这里retry-delay和retry-attempts是从配置yaml文件中读取的。
但是我 在我的代码中动态创建 http 客户端 如下所示。这是因为我在运行时获取了 http 客户端参数(URL、重试属性、标头等)。
如何在此处向我的 http 配置添加重试选项?
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);
基本上在后台 micronaut 使用 AOP Advice for retry using @Retryable annotation
因此,您基本上可以将逻辑移动到方法中并实现逻辑以在异常和延迟时重试该方法。
@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);
}