【发布时间】:2010-09-06 22:17:59
【问题描述】:
如何为每个用户会话存储一个实例对象?
我有一门课来模拟一个复杂的算法。该算法旨在逐步运行。我需要为每个用户实例化这个类的对象。每个用户都应该能够逐步推进他们的实例。
【问题讨论】:
-
你的问题不是很清楚。如果您提及您正在尝试做的事情会有所帮助。
-
Soory,我的英语很差。我现在编辑...
标签: session playframework
如何为每个用户会话存储一个实例对象?
我有一门课来模拟一个复杂的算法。该算法旨在逐步运行。我需要为每个用户实例化这个类的对象。每个用户都应该能够逐步推进他们的实例。
【问题讨论】:
标签: session playframework
您只能将对象存储在缓存中。为此,对象必须是可序列化的。在会话中,您可以将密钥(必须是字符串)存储到缓存中。如果从缓存中删除对象(与会话超时相同),请确保您的代码仍然有效。在http://www.playframework.org/documentation/1.0.3/cache 中有解释。 希望能解决你的问题。
【讨论】:
在会话中存储值:
//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()
【讨论】:
来自播放文档: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);
}
因为它是一个缓存,而不是一个会话,所以您必须考虑到数据可能不再可用,并且有办法从某个地方再次检索它(在这种情况下是消息模型)
无论如何,如果您有足够的内存并且它涉及与用户的短暂交互,则数据应该在那里,如果不是,您可以将用户重定向到向导的开头(您正在谈论某种向导页面,对吧?)
请记住,play 是无状态的 share-nothing 方法,实际上根本没有会话,它只是通过 cookie 处理它,这就是它只能接受大小有限的字符串的原因
【讨论】:
memcached=enabled 和 memcached.host=127.0.0.1:11211 并且不起作用。我收到此错误:“错误:服务器错误服务器遇到错误,无法完成您的请求。如果问题仍然存在,请报告您的问题并提及此错误消息和导致它的查询。”
以下是在会话中保存“对象”的方法。基本上,您将对象序列化/反序列化为 JSON 并将其存储在 cookie 中。
【讨论】: