Vertx 中的定时缓存

Timed caching in Vertx

我刚刚开始使用 Vertx。请问有没有办法store/cache一个响应数据一段时间?

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

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

有没有简单的方法可以做到这一点?

您可以使用缓存(可能有一些 Map)和 Vertx::setTimer 使其在 3 小时后失效。假设您使用的是 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;
 });

您不必再次为 Vert.x 重新发明轮子。有很多工具可以为您进行缓存,Google Guava cache 应该能很好地满足您的需求。

在您的 Verticle 中,您定义了一个 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);