在使用健康检查时,避免调用尚未准备好和重新启动已死的服务的微服务,我们仍然需要保护自己免受其他故障,如超时、网络中断、被调用微服务的bug等等。在本节中,我们将使用一个断路器来保护好消费者。本节的代码位于openshift/hello-microservice-consumer-openshift-breaker目录中。
在这个verticle中,我们使用一个单独的断路器来免受对hello microservice的两个调用的影响。下面的代码使用这个设计;然而,它只是众多可能方法中的一种,例如每次调用都使用一个断路器,或者使用一个断路器保护这两个调用,等等。
private void invokeHelloMicroservice(RoutingContext rc) {
circuit.rxExecuteCommandWithFallback(
future -> {
HttpRequest<JsonObject> request1 = hello.get("/Luke")
.as(BodyCodec.jsonObject());
HttpRequest<JsonObject> request2 = hello.get("/Leia")
.as(BodyCodec.jsonObject());
Single<JsonObject> s1 = request1
.rxSend().map(HttpResponse::body);
Single<JsonObject> s2 = request2
.rxSend().map(HttpResponse::body);
Single
.zip(s1, s2, (luke, leia) -> {
// We have the result of both request in Luke and Leia
return new JsonObject()
.put("Luke", luke.getString("message")
+ " " + luke.getString("served-by"))
.put("Leia", leia.getString("message")
+ " " + leia.getString("served-by"));
})
.subscribe(future::complete, future::fail);
},
error -> new JsonObject().put("message", "hello (fallback, "
+ circuit.state().toString() + ")")
).subscribe(
x -> rc.response().end(x.encodePrettily()),
t -> rc.response().end(t.getMessage()));
}
在发生错误时,我们提供一个回退(fallback)消息,指示断路器状态。这将帮助我们理解发生了什么。部署这个项目使用:
mvn fabric8:deploy -Popenshift
现在我们来讲hello microservice 的规模调整到0,哦们可以在控制界面操作,或者使用命令行:
oc scale --replicas=0 dc hello-microservice
现在如果你刷新消费者页面(http://hello-consumer-reactive-microservices.192.168.64.12.nip.io/\),您应该看到回退的消息。前三个请求显示如下:
{
"message" : "hello (fallback, CLOSED)"
}
一旦失败的次数达到阈值,它将返回:
{
"message" : "hello (fallback, OPEN)"
}
如果您将副本的数量恢复到1。
oc scale --replicas=1 dc hello-microservice
一旦微服务准备好,您应该恢复正常的输出。