2010-09-06 52 views
6

如何存儲一個實例對象foreach用戶會話?playframework中的對象會話

我有一個類來建模一個複雜的算法。此算法旨在逐步運行。我需要爲每個用戶實例化這個類的對象。每個用戶都應該能夠逐步推進他們的實例。

+0

你的問題不是很清楚。如果你提到你正在嘗試做什麼,這將有所幫助。 – 2010-09-07 09:51:14

+0

Soory,我的英語很差。我現在編輯... – barroco 2010-09-07 12:17:41

回答

6

只能存儲在緩存中的對象。這些對象必須是可序列化的。在會話中,您可以將密鑰(必須是字符串)存儲到緩存中。如果對象已從緩存中刪除(與會話超時相同),請確保您的代碼仍然有效。這在http://www.playframework.org/documentation/1.0.3/cache中有解釋。 希望能解決你的問題。

+0

你能給我一個使用示例嗎?,非常感謝 – barroco 2010-09-07 14:43:08

+1

對不起,我不明白我可以在一個沒有記錄在引用文檔。 – niels 2010-09-08 10:53:11

4

存儲值在會話:

//first get the user's session 
//if your class extends play.mvc.Controller you can access directly to the session object 
Session session = Scope.Session.current(); 
//to store values into the session 
session.put("name", object); 

如果你想無效/清除會話對象

session.clear() 
+2

但'對象'應該是一個'字符串',對吧? – barroco 2010-09-07 12:14:56

+1

哦,是的,對象必須是字符串 – plunchete 2010-09-07 17:30:05

+2

然後是不是我的解決方案 – barroco 2010-09-07 17:44:24

0

從遊戲文件:http://www.playframework.org/documentation/1.1.1/cache

Play has a cache library and will use Memcached when used in a distributed environment. 

If you don’t configure Memcached, Play will use a standalone cache that stores data in the JVM heap. Caching data in the JVM application breaks the 「share nothing」 assumption made by Play: you can’t run your application on several servers, and expect the application to behave consistently. Each application instance will have a different copy of the data. 

你可以把任何物體在緩存中,如下面的例子(在這個例子從文檔http://www.playframework.org/documentation/1.1.1/controllers#session,您使用session.getId()保存的消息每個用戶)

public static void index() { 
    List messages = Cache.get(session.getId() + "-messages", List.class); 
    if(messages == null) { 
     // Cache miss 
     messages = Message.findByUser(session.get("user")); 
     Cache.set(session.getId() + "-messages", messages, "30mn"); 
    } 
    render(messages); 
} 

因爲它是一個高速緩存,而不是一個會話,你必須考慮到的數據可能不再可用,並有一定意味着從somehere再次找回它(消息模型,在這種情況下)

無論如何,如果你有足夠的內存,它涉及與用戶的短暫交互,數據應該在那裏,如果不是,你可以將用戶重定向到嚮導的開頭(你正在談論某種精靈頁面,對不對?)

請記住,玩它是無狀態的無共享方法,根本沒有sessión,它下面只是通過cookie處理它,這就是爲什麼它只能接受有限大小的字符串

+0

好的!謝謝。但是我在我的application.conf文件中取消了'memcached = enabled'和'memcached.host = 127.0.0.1:11211'的註釋並且不起作用。我收到此錯誤:「錯誤:服務器錯誤 服務器遇到錯誤,無法完成您的請求。 如果問題仍然存在,請報告您的問題並提及此錯誤消息以及造成它的查詢。 – barroco 2011-02-26 18:56:19

+0

我建議你在遊戲的谷歌組詢問,他們是非常敏感的... http://groups.google。com/group/play-framework – opensas 2011-02-27 06:24:50

+0

我沒有memcaches的使用經驗,但它被認爲是在localhost上偵聽:11211,這是一個服務,應該安裝並運行... – opensas 2011-02-27 06:26:59