我正在编写一个允许人们协作的web应用程序。我希望将我的一些服务范围限定为协作(涉及几个人),而不是任何单独的http会话。我创建了一个自定义Scope来存储bean。为了管理bean生命周期,我跟踪相关的会话ids,如下所示:
protected ConcurrentMap<String,Object> attributes =
new ConcurrentHashMap<String, Object>();
...
@Override
public Object get(String name, ObjectFactory<?> factory) {
synchronized(this.attributes) {
Object scopedObject = this.attributes.get(name);
if (scopedObject == null) {
scopedObject = factory.getObject();
this.attributes.put(name, scopedObject);
RequestAttributes reqAttrs = RequestContextHolder.currentRequestAttributes();
activeSession(name).add(reqAttrs.getSessionId());
}
return scopedObject;
}
}当会话关闭时,我希望从与给定bean名称关联的活动会话列表中删除会话id。当集合变成空的时候,我可以清理。
我认为管理会话关闭的最简单方法是使用HttpSessionListener,但是我的Scope和侦听器之间有一个断开连接。我看到以下可能性:
HttpSessionListener,假设只有一个实例,让它管理订阅列表,并让Scope实例订阅它的事件。但这似乎是多余的,我不喜欢这方面的单例模式。如果Scope中的HttpSession,我可以将Scope添加到存储在会话中的列表中,并让侦听器通知该列表的成员会话即将消失。但是,我不知道如何在Scope实例中获得会话对象(而不仅仅是id)。HttpSessionListener接口,从而直接更新它的状态,但我不知道如何以编程方式注册侦听器。有公开的方法吗?谢谢你的帮忙,
基因
发布于 2011-11-18 21:58:45
由于没有收到任何评论或答复,我选择了选项1,如下所示:
public class SessionMonitor implements HttpSessionListener {
protected final Log logger = LogFactory.getLog(getClass());
protected CopyOnWriteArrayList<SessionEventListener> subscribers = new CopyOnWriteArrayList<SessionEventListener>();
protected ConcurrentHashMap<String,HttpSession> sessions = new ConcurrentHashMap<String,HttpSession>();
protected static SessionMonitor singleton;
public static SessionMonitor soleInstance() throws ConfigurationException {
if (singleton == null)
throw new ConfigurationException("No SessionMonitor instance has been created");
return singleton;
}
public SessionMonitor() {
if (singleton == null)
singleton = this;
}
@Override
public void sessionCreated(HttpSessionEvent e) {
HttpSession session = e.getSession();
this.sessions.putIfAbsent(session.getId(), session);
logger.trace("Registered session " + session.getId());
}
@Override
public void sessionDestroyed(HttpSessionEvent e) {
String sessionId = e.getSession().getId();
this.sessions.remove(sessionId);
for (SessionEventListener listener: subscribers)
listener.sessionEnded(sessionId);
logger.trace("Removed session " + sessionId);
}
public HttpSession getSession(String id) {
return this.sessions.get(id);
}
public void addListener(SessionEventListener listener) {
this.subscribers.add(listener);
logger.trace("Added listener " + listener);
}
public void removeListener(SessionEventListener listener) {
this.subscribers.remove(listener);
logger.trace("Removed listener " + listener);
}
}创建作用域时,它将自己注册到SessionMonitor中。
public ConditionalScope() throws ConfigurationException {
logger.debug("Registering " + this.toString() + " for session monitoring");
SessionMonitor.soleInstance().addListener(this);
}但是,我不清楚何时从Scope中删除SessionMonitor。某种WeakArray会在这里起作用吗?
https://stackoverflow.com/questions/8145856
复制相似问题