2013-06-02 69 views
2

有人可以藉助示例來展示java中如何在播放框架2中使用緩存註釋 我想用他的參數緩存方法的結果;像這樣:播放框架緩存註釋

@Cache(userId, otherParam) 
public static User getUser(int userId, String otherParam){ 
return a User from dataBase if it isn't in cache. 
} 

也許教程可用?

感謝您的幫助。

回答

1

@Cached註釋不適用於每個方法調用。它僅適用於操作,而且,不能將參數用作緩存鍵(它只是靜態的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); 
} 

要小心,當你建立你的緩存鍵,以避免命名衝突,因爲它們在整個應用程序中共享。