Find websocket session by id in Java EE 7

旧巷老猫 提交于 2020-01-14 10:09:43

问题


I've read Java EE documentation and for me is unclear one thing. According to API, the only way to find another Session is a code like this: (assuming that we've identifier of other 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;
}

But when we've thousands of users, this code is a performance bottleneck.

So, is there a way to get Session by id fast without using own ConcurrentHashMap for this? Or maybe some application server has undocummented feature for this (for me Wildfly would be great)?


回答1:


You can do something like:

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());
    }
}


来源:https://stackoverflow.com/questions/27037570/find-websocket-session-by-id-in-java-ee-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!