Pig Cloud遇到websocket不能实现同一个用户不同浏览器接受到广播的消息解决方案

自定义SecuritySessionKeyGenerator类,为每个客户端连接建立唯一的key

java 复制代码
package com.pig4cloud.plugin.websocket.custom;

import com.pig4cloud.plugin.websocket.holder.SessionKeyGenerator;
import org.springframework.web.socket.WebSocketSession;

import java.util.UUID;
public class SecuritySessionKeyGenerator implements SessionKeyGenerator {
	@Override
	public Object sessionKey(WebSocketSession webSocketSession) {
		Object user = webSocketSession.getAttributes().get("USER_KEY_ATTR_NAME");
		// 添加随机后缀使每个连接键唯一
		return user != null ? user + "-" + UUID.randomUUID().toString() : null;
	}
}

重写WebSocketSessionHolder类方法

java 复制代码
package com.pig4cloud.plugin.websocket.holder;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;

import org.springframework.web.socket.WebSocketSession;

public final class WebSocketSessionHolder {
	// 仅修改这一行:将Value改为Set类型
	private static final Map<String, Set<WebSocketSession>> USER_SESSION_MAP = new ConcurrentHashMap<>();

	private WebSocketSessionHolder() {
	}

	public static void addSession(Object sessionKey, WebSocketSession session) {
		// 修改为支持多会话的添加方式
		USER_SESSION_MAP.computeIfAbsent(sessionKey.toString(),
				k -> new CopyOnWriteArraySet<>()).add(session);
	}

	public static void removeSession(Object sessionKey) {
		// 移除时不再自动清除所有会话
		Set<WebSocketSession> sessions = USER_SESSION_MAP.get(sessionKey.toString());
		if (sessions != null) {
			sessions.removeIf(s -> !s.isOpen()); // 只移除已关闭的连接
			if (sessions.isEmpty()) {
				USER_SESSION_MAP.remove(sessionKey.toString());
			}
		}
	}

	// 保持原有方法签名不变(兼容现有调用)
	public static WebSocketSession getSession(Object sessionKey) {
		Set<WebSocketSession> sessions = USER_SESSION_MAP.get(sessionKey.toString());
		return sessions != null ? sessions.stream().findFirst().orElse(null) : null;
	}

	// 新增方法:获取用户的所有会话
	public static Set<WebSocketSession> getSessions(Object sessionKey) {
		return USER_SESSION_MAP.getOrDefault(sessionKey.toString(), Collections.emptySet());
	}

	// 保持原有方法不变
	public static Collection<WebSocketSession> getSessions() {
		List<WebSocketSession> allSessions = new ArrayList<>();
		USER_SESSION_MAP.values().forEach(allSessions::addAll);
		return allSessions;
	}

	// 保持原有方法不变
	public static Set<String> getSessionKeys() {
		return USER_SESSION_MAP.keySet();
	}
}
相关推荐
wen__xvn15 分钟前
计算机网络1-5:计算机网络的性能指标
网络·计算机网络
学习网安的doro23 分钟前
3a服务器的基本功能1之身份认证
服务器·网络·学习·安全·身份认证·ac
搬码临时工33 分钟前
如何设置端口映射?防火墙/路由器/纯软件工具多种常用方案步骤,确保任意内网ip端口映射公网访问到
网络·网络协议·tcp/ip
m0_659394002 小时前
Beelzebub靶机
网络
结城3 小时前
HTTP 与 HTTPS 的区别深度解析:从原理到实践
网络协议·http·https
暗流者4 小时前
Mac 洪泛攻击笔记总结补充
网络
腾科张老师4 小时前
路由的类型
网络
userLee5 小时前
家庭网络硬件
网络协议
DemonAvenger6 小时前
大规模Go网络应用的部署与监控
网络协议·架构·go