POM文件增加:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
Websocket配置类:(放到config目录下,没有他的话,前端会订阅会失败)
package com.sa.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
/**
* 注入ServerEndpointExporter,
* 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
Websocket类:(其中@ServerEndpoint("/websocket/businessName/{clientName}")是前端使用的消息订阅链接,可以根据自身业务更换。我在写的时候把这个链接做成了免登录可用,可以根据实际情况自行决定)
package com.sa.common;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hstech.redis.RedisCache;
import com.hstech.util.common.spring.SpringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.TimeUnit;
/**
* @Classname: WebSocket
* @Description: websocket监听
* @author: 流泪兔兔头
* @date: 2022/3/4 9:14
*/
@Component
@ServerEndpoint("/websocket/businessName/{clientName}")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets = new CopyOnWriteArraySet<>();
private static ConcurrentHashMap<Session, String> webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session) {
// 当前端订阅时,执行这个方法
this.session = session;
webSockets.add(this);
System.out.println("【websocket消息】有新的连接,总数为:" + webSockets.size());
}
@OnClose
public void onClose() {
// 当有订阅的页面关闭时,执行这个方法
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:" + webSockets.size());
}
@OnMessage
public void onMessage(String message) {
// 当前端主动发送消息时,订阅这个方法,发送名字,存储名字和session
JSONObject msgJson = JSON.parseObject(message);
String name = msgJson .getString("name");
webSocketMap.put(session, name);
System.out.println("【websocket消息】收到客户端消息:" + message);
}
// 自定义方法,全部发送
public void sendMessageToAll(String clientName, String message) {
JSONObject msg = new JSONObject();
msg.put("msg", message);
webSockets.forEach(webSocket -> webSocket.session.getAsyncRemote().sendText(msg.toJSONString()));
}
// 自定义方法,根据名字匹配发送
public void sendMessageByName(String name, String message) {
JSONObject msg = new JSONObject();
msg.put("msg", message);
for(Map.Entry<Session, String> entry : webSocketMap.entrySet()) {
if(StrUtil.equals(entry.getValue(), name)) {
entry.getKey().getAsyncRemote().sendText(msg.toJSONString());
}
}
}
}
当想要发送消息时,使用如下代码:
// 根据情况也可以换成@Resource注入形式
WebSocket webSocket = SpringUtil.getBean(WebSocket.class);
// 调用自定义的根据名称匹配发送,其中clientName为前端订阅时发送过来的名
webSocket.sendMessageByName(clientName,message);