我有下面一段代码:
package starter;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Future;
public class MainVerticle extends AbstractVerticle {
@Override
public void start() {
vertx.createHttpServer().requestHandler(req -> req.response().end("Hello Vert.x!")).listen(8080);
cacheFirst("key", Future.future(h -> {
System.out.println("Call external API");
h.complete("Call external API");
}))
.onComplete(h -> System.out.println("Success"))
.onFailure(t -> System.out.println("Failed"));
}
private Future<String> cacheFirst(String key, Future<String> task) {
Future<String> getCache = Future.future(h -> {
h.complete("ABCXYZ");
});
return getCache.onSuccess(res -> {
System.out.println("Data from cache: " + res);
}).onFailure(t -> {
task.onSuccess(res -> {
System.out.println("Store task result to cache");
}).onFailure(tt -> {
System.out.println("Do nothing");
});
});
}
}
期望控制台输出:
Data from cache: ABCXYZ
Success
实际控制台输出:
Call external API
Data from cache: ABCXYZ
Success
在函数start
中,我如何将Future
作为参数传递给cacheFirst
函数而不执行它?
在实际场景中,cacheFirst
函数将首先尝试从缓存存储中获取数据,如果找到了数据,则不需要执行提供的未来(Future<string> task
),例如,调用对外部API的请求。
扬声器:https://github.com/triet-truong/vertx-application
只需将其包装在Supplier
中就会产生预期的结果!
https://github.com/triet-truong/vertx-application/commit/6391c1b5d6b5f0e9b927ab0a9834b3ce6f0edf7f
cacheFirst("key", () -> Future.future(h -> {
System.out.println("Call external API");
h.complete("Call external API");
}))
.onComplete(h -> System.out.println("Success"))
.onFailure(t -> System.out.println("Failed"));
private Future<String> cacheFirst(String key, Supplier<Future<String>> task) {
Future<String> getCache = Future.future(h -> {
h.complete("ABCXYZ");
});
return getCache.onSuccess(res -> {
System.out.println("Data from cache: " + res);
}).onFailure(t -> {
task.get().onSuccess(res -> {
System.out.println("Store task result to cache");
}).onFailure(tt -> {
System.out.println("Do nothing");
});
});
}