mirror of
https://github.com/continew-org/continew-starter.git
synced 2025-09-08 16:57:09 +08:00
feat(messaging/websocket): 新增批量发送消息方法
This commit is contained in:
@@ -19,6 +19,7 @@ package top.continew.starter.messaging.websocket.dao;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* WebSocket 会话 DAO
|
||||
@@ -58,4 +59,12 @@ public interface WebSocketSessionDao {
|
||||
* @since 2.12.1
|
||||
*/
|
||||
Collection<WebSocketSession> listAll();
|
||||
|
||||
/**
|
||||
* 获取所有会话 ID
|
||||
*
|
||||
* @return 所有会话 ID
|
||||
* @since 2.12.1
|
||||
*/
|
||||
Set<String> listAllSessionIds();
|
||||
}
|
||||
|
@@ -20,6 +20,7 @@ import org.springframework.web.socket.WebSocketSession;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
@@ -51,4 +52,9 @@ public class WebSocketSessionDaoDefaultImpl implements WebSocketSessionDao {
|
||||
public Collection<WebSocketSession> listAll() {
|
||||
return SESSION_MAP.values();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> listAllSessionIds() {
|
||||
return SESSION_MAP.keySet();
|
||||
}
|
||||
}
|
||||
|
@@ -16,6 +16,7 @@
|
||||
|
||||
package top.continew.starter.messaging.websocket.util;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -25,6 +26,8 @@ import org.springframework.web.socket.WebSocketSession;
|
||||
import top.continew.starter.messaging.websocket.dao.WebSocketSessionDao;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* WebSocket 工具类
|
||||
@@ -62,6 +65,18 @@ public class WebSocketUtils {
|
||||
sendMessage(session, new TextMessage(message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量发送消息
|
||||
*
|
||||
* @param clientIds 客户端 ID 列表
|
||||
* @param message 消息内容
|
||||
* @since 2.12.1
|
||||
*/
|
||||
public static void sendMessage(List<String> clientIds, String message) {
|
||||
Collection<String> sessionIds = CollUtil.intersection(SESSION_DAO.listAllSessionIds(), clientIds);
|
||||
sessionIds.parallelStream().forEach(sessionId -> sendMessage(sessionId, message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息给所有客户端
|
||||
*
|
||||
|
Reference in New Issue
Block a user