§The Play cache API
Caching data is a typical optimization in modern applications, and so Play provides a global cache.
Note: An important point about the cache is that it behaves just like a cache should: the data you just stored may just go missing.
For any data stored in the cache, a regeneration strategy needs to be put in place in case the data goes missing. This philosophy is one of the fundamentals behind Play, and is different from Java EE, where the session is expected to retain values throughout its lifetime.
Play provides a CacheApi implementation based on Caffeine and a legacy implementation based on Ehcache 2.x. For in-process caching Caffeine is typically the best choice. If you need distributed caching, there are third-party plugins for memcached and redis.
§Importing the Cache API
Play provides separate dependencies for the Cache API and for the Caffeine and Ehcache implementations.
§Caffeine
To get the Caffeine implementation, add caffeine to your dependencies list:
libraryDependencies ++= Seq(
caffeine
)
This will also automatically set up the bindings for runtime DI so the components are injectable.
§EhCache
To get the EhCache implementation, add ehcache to your dependencies list:
libraryDependencies ++= Seq(
ehcache
)
This will also automatically set up the bindings for runtime DI so the components are injectable.
§Custom Cache Implementation
To add only the API, add cacheApi to your dependencies list.
libraryDependencies ++= Seq(
cacheApi
)
The API dependency is useful if you’d like to define your own bindings for the Cached helper and AsyncCacheApi, etc., without having to depend on any specific cache implementation. If you’re writing a custom cache module you should use this.