Vertx中的定时缓存

问题描述 投票:0回答:2

我刚开始使用Vertx。我想知道是否可以在一段时间内存储/缓存响应数据吗?

例如,用户第一次调用我的API时,它将查询服务器上的数据库并返回数据。我想将此数据保存/缓存到服务器上的本地文件(或内存)中,例如3个小时。在这3个小时内,如果任何其他用户再次调用该API,它将使用缓存的数据代替。 3小时后,缓存的数据将重置。

我曾尝试在Google上搜索诸如Vertx Redis或StaticHandler之类的解决方案,但它们似乎过于复杂,似乎不符合我的需求?

有没有简单的方法可以实现这一目标?

java vert.x
2个回答
0
投票

您可以使用缓存(可能有一些Map),并在3小时后将Vertx::setTimer设为无效。假设您正在使用Router

 router.get("/things/:id").handler(rc -> {
     String id = rc.pathParam("id");
     List result = cache.getThing(id);
     if (result == null) {
       result = getThingFromDatabase(id);
       cache.saveThing(result);
       vertx.setTimer(10800000, t -> { // <-- 3 hours
           cache.invalidateThing(id);
       });
     }
     return result;
 });

0
投票

您不必再次为Vert.x重新发明轮子。有很多工具可以为您进行缓存,Google Guava cache是非常适合您需求的工具。

在您的顶点上,定义一个cache并通过它访问数据库。缓存将完成其余工作:

LoadingCache<Key, Graph> cache = CacheBuilder.newBuilder()
       .expireAfterWrite(3, TimeUnit.HOURS)
       .build(
           new CacheLoader<Key, SomeClass>() {
             @Override
             public SomeClass load(Key key) throws AnyException {
               return loadYourData(key);
             }
           });

然后在需要获取数据时:

SomeClass obj = cache.get(key);
© www.soinside.com 2019 - 2024. All rights reserved.