Last active
January 13, 2021 17:45
-
-
Save ptomaszek/050c9271894b9daa253de5c4e21508e1 to your computer and use it in GitHub Desktop.
Caffeine cache in Vert.x; mapping between Future and CompletableFuture;
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.github.benmanes.caffeine.cache.AsyncCacheLoader | |
import com.github.benmanes.caffeine.cache.AsyncLoadingCache | |
import com.github.benmanes.caffeine.cache.Caffeine | |
import groovy.util.logging.Slf4j | |
import io.vertx.core.Context | |
import io.vertx.core.Future | |
import io.vertx.core.Promise | |
import io.vertx.core.Vertx | |
import java.time.Duration | |
import java.util.concurrent.CompletableFuture | |
import java.util.concurrent.Executor | |
@Slf4j | |
class CacheableClientImpl implements Client { | |
private AsyncLoadingCache<Long, Map> cache | |
private Client client | |
CacheableClientImpl(Vertx vertx) { | |
client = new ClientImpl(vertx) | |
Context context = vertx.getOrCreateContext() | |
Executor contextExecutor = cmd -> context.runOnContext(v -> cmd.run()) | |
this.cache = Caffeine<Long, Map>.newBuilder() | |
.executor(contextExecutor) | |
.expireAfterWrite(Duration.ofHours(1)) | |
.maximumSize(1_000) | |
.<Long, Map> buildAsync(asyncLoaderOf { Long id -> client.getInfo(id) }) | |
} | |
@Override | |
Future<Map> getInfo(Long id) { | |
return toFuture(cache.get(id)) | |
} | |
private static AsyncCacheLoader asyncLoaderOf(Closure<Future> closure) { | |
return (key, executor) -> toCompletableFuture(closure(key)) | |
} | |
private static <T> CompletableFuture<T> toCompletableFuture(Future<T> future) { | |
CompletableFuture<T> cf = new CompletableFuture<>() | |
future | |
.onSuccess { cf.complete(it) } | |
.onFailure { cf.completeExceptionally(it) } | |
return cf | |
} | |
private static <T> Future<T> toFuture(CompletableFuture<T> future) { | |
Promise p = Promise.promise() | |
Objects.requireNonNull(future).whenComplete((res, err) -> { | |
if (err != null) { | |
p.fail(err) | |
} else { | |
p.complete(res) | |
} | |
}) | |
return p.future() | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import io.vertx.core.Future | |
interface Client { | |
abstract Future<Map<String, Object>> getInfo(Long id) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment