有人可以通过示例了解java中play框架2中的缓存注释是如何工作的 我想用他的参数缓存方法的结果;像这样的东西:
@Cache(userId, otherParam)
public static User getUser(int userId, String otherParam){
return a User from dataBase if it isn't in cache.
}
也许教程可用?
感谢您的帮助。
答案 0 :(得分:1)
@Cached
注释不适用于每个方法调用。它仅适用于Actions,而且,您不能将参数用作缓存键(它只是静态String
)。如果您想知道它是如何工作的,请查看play.cache.CachedAction
源代码。
相反,您必须使用Cache.get()
,检查结果是否为空,然后检查Cache.set()
或Cache.getOrElse()
,Callable
,代码如下:
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);
}
构造缓存键时要小心,以避免命名冲突,因为它们在整个应用程序中共享。