在Java EE 7中按ID查找websocket会话

时间:2014-11-20 10:43:48

标签: java performance java-ee websocket java-ee-7

我已经阅读过Java EE文档,对我来说还不清楚。根据API,找到另一个Session的唯一方法是这样的代码:(假设我们是其他会话的标识符):

import javax.websocket.Session;
...
private static Session findOtherSessionById(Session user, String id) {
    for (Session session : user.getOpenSessions()) {
        if (id.equals(session.getId())) {
            return session;
        }
    }
    return null;
}

但是当我们有成千上万的用户时,这段代码就是性能瓶颈。

那么,有没有办法快速获取Session的ID而不使用自己的ConcurrentHashMap?或者也许某些应用程序服务器具有未填充功能(对我来说Wildfly会很棒)?

1 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

Map<String, Session> map = new HashMap<>();
static Map<String, Session> peers = Collections.synchronizedMap(map);

@OnOpen
public void onOpen(Session session) {
   peers.add(session.getId(), session);
}

@OnClose
public void onClose(Session session) {
    peers.remove(session.getId());
}

private static Session findOtherSessionById(Session user, String id) {
    if (peers.containsKey(user.getId()) {
        return peers.get(user.getId());
    }
}