skip to Main Content

I’ve just been starting out with Vertx. I wonder if there’s a way to store/cache a response data for a period of time?

For example, the first time a user calls my API, it will query the database on the server and return a data. I want to save/cache this data to a local file (or memory) on the server for, for example, 3 hours. During these 3 hours, if any other user make another call to the API, it will use the cached data instead. After 3 hours, the cached data reset.

I tried searching on Google for solutions like Vertx Redis, or StaticHandler, but they seem over-complicated, and don’t seem to match my needs?

Is there a simple way to achieve this?

2

Answers


  1. You could use a cache (with some Map maybe) and Vertx::setTimer to invalidate it after 3 hours. Assuming you are using 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;
     });
    
    Login or Signup to reply.
  2. You don’t have to reinvent wheel for Vert.x again. There are plenty of tools out there to do caching for you and Google Guava cache is the one that should suite your need very well.

    In your verticle you define a cache and access your DB though it. The cache does the rest:

    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);
                 }
               });
    

    then whenever you need to get your data:

    SomeClass obj = cache.get(key);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search