是否有一种更理智的方式来编写以下超级简单的set / get / close测试程序?请注意,我必须复制Redis关闭代码并将其包含在set error path和get complete path中。
import io.vertx.core.Vertx;
import io.vertx.redis.RedisClient;
import io.vertx.redis.RedisOptions;
public class RedisTest {
public static void main(String[] args) throws Exception {
Vertx vertx = Vertx.vertx();
String host = "localhost";
final RedisClient client = RedisClient.create(vertx,
new RedisOptions().setHost(host));
client.set("key", "value", r -> {
if (r.succeeded()) {
System.out.println("key stored");
client.get("key", s -> {
if (s.succeeded()) {
System.out.println("Retrieved value: " + s.result());
} else {
System.out.println("Connection or Operation Failed " + s.cause());
}
System.out.println("Closing Redis connection");
client.close(t -> {
if (s.succeeded()) {
System.out.println("Redis closed successfully.");
} else {
System.out.println("Connection or Operation Failed " + t.cause());
}
System.out.println("Closing vertx");
vertx.close();
});
});
} else {
System.out.println("Connection or Operation Failed " + r.cause());
System.out.println("Closing Redis connection");
client.close(s -> {
if (s.succeeded()) {
System.out.println("Redis closed successfully.");
} else {
System.out.println("Connection or Operation Failed " + s.cause());
}
System.out.println("Closing vertx");
vertx.close();
});
}
});
System.out.println("Exiting main");
}
}
答案 0 :(得分:2)
我建议看看被动api io.vertx.rxjava.redis.RedisClient
。它是链式计算的优秀(主要目的)。
例如(我未测试此代码):
client.rxSet("key", "value")
.flatMap(r -> client.rxGet("key"))
//calls on error or success
.doAfterTerminate(() -> {
client.rxClose();
vertx.close();
})
.subscribe(
success -> System.out.println("Chain completed"),
//all errors will be there
error -> System.out.println(error.getMessage())
);