Cacheman is a Cache Manager for Play! Framework. It simplifies the management of cache keys within session or global scopes
and provides tools for describing the generation of the values for cache keys.
To install Cacheman, you can use the modules repository:
play install cacheman-<required version>
If you are using Play! 1.2 or above, you can add it to your dependencies.
- play -> cacheman <required version>
A sample application is included in the test-app folder.
Create enums for the session and global scope cache keys. A sample enum named SampleCacheKey is included in the module. Below is a sample enum for global scope cache keys. Two enums, SessionCacheKey and GlobalCacheKey is sufficient for a common application.
A CacheAdapter is used for defining the generation of the values for the cache keys. You can pass a function or a static method of the GenericModel to the CacheAdapter. Then you can use CacheManager.get(GlobalCacheKey.USER_COUNT) or CacheManager.get(GlobalCacheKey.USER, username) to get the value. If the value is present in the cache then CacheManager.get immediately returns the value. If the value is not present in the cache then the value is generated and stored in the cache, then the generated value is returned.
package cache;
import models.User;
import cachemanager.cache.CacheAdapter;
import cachemanager.cache.CacheKey;
import cachemanager.common.Function;
public enum GlobalCacheKey implements CacheKey
{
USER(new CacheAdapter(new Function<String, User>()
{
@Override
public User apply(String username)
{
return User.findByUsername(username);
}
},
"8h")),
USER_COUNT(new CacheAdapter(User.class, "count", "5mn"));
private CacheAdapter adapter;
private GlobalCacheKey(CacheAdapter adapter)
{
this.adapter = adapter;
}
@Override
public CacheScope scope()
{
return CacheScope.GLOBAL;
}
@Override
public String key()
{
return this.name();
}
@Override
public CacheAdapter adapter()
{
return adapter;
}
}