Reputation: 131
Can somebody exlain, with a sample, how works the cache annotation in play framework 2 in java I would like to cache the result of the method with his parameters; something like this:
@Cache(userId, otherParam)
public static User getUser(int userId, String otherParam){
return a User from dataBase if it isn't in cache.
}
Maybe a tutorial is available?
Thanks for your help.
Upvotes: 3
Views: 1635
Reputation: 4181
The @Cached
annotation doesn't work for every method call. It only works for Actions and moreover, you can't use parameters as a cache key (it's only a static String
). If you want to know how it works, look at the play.cache.CachedAction
source code.
Instead, you will have to use either Cache.get()
, check if result is null and then Cache.set()
or the Cache.getOrElse()
with a Callable
with a code like :
public static User getUser(int userId, String otherParam){
return Cache.getOrElse("user-" + userId + "-" + otherParam, new Callable<User>() {
@Override
public User call() throws Exception {
return getUserFromDatabase(userId, otherParam);
}
}, DURATION);
}
Be careful when you construct your cache keys to avoid naming-collision as they are shared across the whole application.
Upvotes: 2