我正在使用java websocket连接服务器,连接后,我将会话存储到如下的hashmap中:
if (CollectionUtils.isNotEmpty(roomPlayCount)) {
roomPlayCount.stream().forEach(item -> {
Integer currentOnlineCount = item.getOnlineCount();
Integer roomSeatsCount = getRoomMaxAmount(roomTypeResponses, item.getRoomId());
Double ratio = ((double) currentOnlineCount / roomSeatsCount) * 100;
if (ratio.intValue() < playRatio) {
createWebsocketConnection(token, item.getRoomId(), userInfo);
}
});
}
这是保存功能:
private void createWebsocketConnection(String token, Long roomTypeId, Response<UserInfoResponse> userInfo) {
WebsocketClientEndpoint websocketClientEndpoint = RobotClientOperation.robotNewConnect(roomTypeId, token);
if (StringUtils.isNotBlank(token) && websocketClientEndpoint != null) {
Long userId = userInfo.getResult().getUserId();
String sessionId = websocketClientEndpoint.userSession.getId();
if (!websockSessions.containsKey(token)) {
if (!isDulplicateUser(userId)) {
ClientSession clientSession = new ClientSession(userId, token, websocketClientEndpoint.userSession);
websockSessions.put(sessionId, clientSession);
}
} else {
log.error("获取到了重复用户:" + JSON.toJSONString(userInfo));
}
}
}
但是当我从服务器收到消息时,我无法从id中获取会话。
if (PlayRoomOperate.websockSessions.get(session.getId()) == null) {
//log.warn("can not find record:" + session.getId());
return;
}
会话ID是否已更改?这会发生什么?昨天工作正常。我发现在将create操作移到foreach外部时,它工作正常。当将内部foreach移动时,情况发生了。