feat(messaging/websocket): 新增发送消息给所有客户端方法

This commit is contained in:
2025-05-18 20:42:24 +08:00
parent adaf475835
commit fa2cdf4f80
3 changed files with 26 additions and 0 deletions

View File

@@ -18,6 +18,8 @@ package top.continew.starter.messaging.websocket.dao;
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketSession;
import java.util.Collection;
/** /**
* WebSocket 会话 DAO * WebSocket 会话 DAO
* *
@@ -48,4 +50,12 @@ public interface WebSocketSessionDao {
* @return 会话信息 * @return 会话信息
*/ */
WebSocketSession get(String key); WebSocketSession get(String key);
/**
* 获取所有会话
*
* @return 所有会话
* @since 2.12.1
*/
Collection<WebSocketSession> listAll();
} }

View File

@@ -18,6 +18,7 @@ package top.continew.starter.messaging.websocket.dao;
import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.WebSocketSession;
import java.util.Collection;
import java.util.Map; import java.util.Map;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
@@ -45,4 +46,9 @@ public class WebSocketSessionDaoDefaultImpl implements WebSocketSessionDao {
public WebSocketSession get(String key) { public WebSocketSession get(String key) {
return SESSION_MAP.get(key); return SESSION_MAP.get(key);
} }
@Override
public Collection<WebSocketSession> listAll() {
return SESSION_MAP.values();
}
} }

View File

@@ -62,6 +62,16 @@ public class WebSocketUtils {
sendMessage(session, new TextMessage(message)); sendMessage(session, new TextMessage(message));
} }
/**
* 发送消息给所有客户端
*
* @param message 消息内容
* @since 2.12.1
*/
public static void sendMessage(String message) {
SESSION_DAO.listAll().forEach(session -> sendMessage(session, message));
}
/** /**
* 发送消息 * 发送消息
* *