保留Java WebSocket会话以供其他servlet稍后检索的最佳方法是什么?

保留Java WebSocket会话以供其他servlet稍后检索的最佳方法是什么?,java,session,servlets,websocket,java-websocket,Java,Session,Servlets,Websocket,Java Websocket,我有一个JavaWebSocket,它当前将会话缓存在一个静态字段中,以便其他servlet可以调用一个静态方法向任何侦听器发送消息(作为事件的推送通知)。就像: @ServerEndpoint("/events") public class Events { // collection containing all the sessions private static final Set<Session> sessions = Collections.synchroni

我有一个JavaWebSocket,它当前将会话缓存在一个静态字段中,以便其他servlet可以调用一个静态方法向任何侦听器发送消息(作为事件的推送通知)。就像:

@ServerEndpoint("/events")
public class Events {

  // collection containing all the sessions
  private static final Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>());

  @OnOpen
  public void onOpen(final Session session) {
        // cache the new session
        sessions.add(session);
        ...
  }

  @OnClose
  public void onClose(final Session session) {
        // remove the session
        sessions.remove(session);
  }

  public static void notify(String message) {
        synchronized(sessions) {
          for (Session s : sessions) {
            if (s.isOpen()) {
              try {
                    // send the message
                    s.getBasicRemote().sendText(message);
              } catch (IOException ex) { ... }
            }
          }
        }
  }
}
但是静态变量是最好的方法吗?是否没有内置注释用于缓存会话或服务器端点以供其他servlet检索(可能通过
@Context
变量或其他方式)


静态变量似乎不是处理这个问题的最佳方式。

如果这个问题仍然在您的议事日程上,我也很感兴趣。在我们的解决方案中,我们使用了一个
@ApplicationScope
,它充当“会话处理程序”。@ApplicationScope被注入@ServerEndpoint。那就像你写的一样。我们避免在@ServerEndpoint中使用静态字段,因为Websocket以一种非常奇怪、有时不可预测的方式处理线程。如果这个问题仍然在您的议事日程上,我也很感兴趣。在我们的解决方案中,我们使用了一个
@ApplicationScope
,它充当“会话处理程序”。@ApplicationScope被注入@ServerEndpoint。那就像你写的一样。我们避免在@ServerEndpoint中使用静态字段,因为Websocket以一种非常奇怪、有时不可预测的方式处理线程
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
    Events.notify( "some message" );
}