微服务的健壮性实现与测试策略
1. 实现健壮性模式
1.1 使用 Polly 进行重试设置
在微服务的协作中,通信失败是常见的情况。为了处理这种失败,我们可以使用 Polly 库来设置重试策略。以下是一个简单的示例代码:
httpClient.BaseAddress = new Uri($"http://{this.hostName}");
var response = await
httpClient.PostAsync("/users/",
new StringContent(JsonConvert.SerializeObject(newUser),
Encoding.UTF8,
"application/json"));
ThrowOnTransientFailure(response);
return response;
private static void ThrowOnTransientFailure(HttpResponseMessage response)
{
if (((int) response.StatusCode) < 200 || ((int) response.StatusCode) > 499)
throw new Exception(response.StatusCode.ToString());
}
在这个代码中,我们首先设置了 HttpClient 的基础地址,然后发送一个 POST 请求到 /users/ 端点。 ThrowOn
超级会员免费看
订阅专栏 解锁全文
167万+

被折叠的 条评论
为什么被折叠?



