一对一, 在线人数
可以在线人员发送信息,扩展:可强退在线人员
@Slf4j
@ServerEndpoint(value = "/websocket/online/{userId}", configurator = SpringWebSocketConfig.class)
@Component
public class OnlineUserWebSocket {
private static AtomicInteger onlineCount = new AtomicInteger(0); // 记录当前在线连接数
private static Map<String, Session> clients = new ConcurrentHashMap<>(); // 存放所有在线的客户端
private static int timeout = 8*3600;
private Session session;
private String userId = "";
private Integer roleId = 0;
public String getUserKey() {
return CacheConstant.ONLINE_USER + userId;
}
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session, EndpointConfig config) throws Exception {
if (!ConfigServiceUtils.getOnOrOff(ConfigConstant.SYS_ONLINE_USER_WEBSOCKET_OR_NOT)) {
log.error("系统未开启在线用户 WebSocket");
onClose(session);
return;
}
this.userId = userId;
this.session = session;
Object obj = JSONObject.parseObject(JsonUtils.mapper(session.getUserPrincipal())).get("object");
UserPrincipal userPrincipal = JSON.toJavaObject((JSON) obj, UserPrincipal.class);
if (Objects.isNull(userPrincipal) || StringUtils.isEmpty(userId)) {
sendMessage("Fail...onOpen", session);
onClose(session);
return;
}
this.roleId = userPrincipal.getRoleId();
if (clients.containsKey(userId)) {
CacheUtils.delete(getUserKey());
clients.remove(userId);
} else {
onlineCount.incrementAndGet();
}
CacheUtils.set(getUserKey(), obj, timeout);
clients.put(userId, session);
log.info("用户:{}, ID: {}, 连接打开,当前在线人数为:{}", userPrincipal.getUsername(), userId, onlineCount.get());
sendMessage("Connect success...", session, true);
}
@OnClose
public void onClose(Session session) {
log.info("用户ID: {},连接关闭,当前在线人数为:{}", userId, onlineCount.get());
if (clients.containsKey(userId)) {
clients.remove(userId);
CacheUtils.delete(getUserKey());
onlineCount.decrementAndGet();
}
}
@OnMessage
public void OnMessage(String message, Session session) {
log.info("收到客户端[{}]的信息:{}", userId, message);
try {
WebSocketMessage webSocketMessage = JSON.parseObject(message, WebSocketMessage.class);
log.info(webSocketMessage.toString());
if (webSocketMessage != null) {
Session toSession = clients.get(webSocketMessage.getUserId());
if (toSession != null) {
this.sendMessage(webSocketMessage.getMessage(), toSession);
} else {
log.info("发送信息失败,没有找到配置的用户:{}", webSocketMessage.getUserId());
}
}
} catch (Exception e) {
log.error("解析失败:{}", e);
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("SessionID:" + session.getId() + ",Message:" + error.getMessage());
}
private void sendMessage(String message, Session toSession) {
sendMessage(message, toSession, false);
}
private void sendMessage(String message, Session toSession, boolean always) {
try {
AjaxResult result = new AjaxResult();
result.put(result.CODE_TAG, this.code);
result.put(result.MSG_TAG, message);
log.info("服务器给客户端, 发送者:{},拉收者:{}", session.getId(), toSession.getId());
if (always || !session.getId().equals(toSession.getId())) {
toSession.getBasicRemote().sendText(JSON.toJSONString(result));
}
} catch (Exception e) {
log.error("服务器发送信息给客户端失败:{}", e);
}
}
}
实体
@Data
public class WebSocketMessage {
public String userId;
public String message;
}