在Java EE 7中按ID查找websocket会话 [英] Find websocket session by id in Java EE 7

查看:427
本文介绍了在Java EE 7中按ID查找websocket会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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)?

推荐答案

你可以这样做:

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

这篇关于在Java EE 7中按ID查找websocket会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆