SRobertJames
SRobertJames

Reputation: 9253

Play - Sharing objects among requests with no need for persistence

In my Play application, I need to share some objects in between several requests, but have no need for any type of long term persistence. The objects are too big to be stuffed into a cookie. I could serialize them to a relational database, but that seems to heavy for my needs: it would suffice to somehow say "Keep this object around for 10 minutes, make it accessible to all threads, then throw it out"

How can I do this?

Upvotes: 0

Views: 71

Answers (2)

Michael Zajac
Michael Zajac

Reputation: 55569

Play's cache API is more than enough for this. It uses EHCache (an in-memory cache) as it's default implementation.

Play Scala:

import play.api.cache.Cache

val hugeList: List[String] = ...

Cache.set("keyName", hugeList, 600) // Caches `hugeList` as "keyName" for 10 minutes (600 seconds)

Cache.getAs[List[String]]("keyName") // Returns `Option[List[String]]` with the value if "keyName" is cached, otherwise `None`.

Cache.remove("keyName") // Removes this key from the cache.

Play Java:

import play.cache.Cache;

Cache.set("keyName", hugeList, 600); // Works exactly the same as the scala version.

Cache.get("keyName");  // Returns the cached value or `null`.

Cache.remove("keyName");  // Same as scala version.

Also be sure to include cache within libraryDependencies in your build.sbt or Build.scala.

API Docs: Scala, Java.

Upvotes: 0

Mon Calamari
Mon Calamari

Reputation: 4463

Google Guava collections are good match for your requirements. You can create in memory cache with expiration. Guava Explained and example from the link:

LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder()
   .maximumSize(1000)
   .expireAfterWrite(10, TimeUnit.MINUTES)
   .removalListener(MY_LISTENER)
   .build(
       new CacheLoader<Key, Graph>() {
         public Graph load(Key key) throws AnyException {
           return createExpensiveGraph(key);
         }
       });

Alternatively, you could implement the cache yourself with ConcurrentHashMap.

Upvotes: 1

Related Questions