一. 添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.4.4</version>
</dependency>
二. 添加websocket服务节点的配置
@Configuration
public class WebsocketConfig {
@Bean
public ServerEndpointExporter getServerEndpointExporter() {
return new ServerEndpointExporter();
}
}
三. 定义websocket服务
@Component
@ServerEndpoint("/ws/{oid}")
public class WebSocketServer {
private static ConcurrentHashMap<String, Session> sessionMap = new ConcurrentHashMap<>();
@OnOpen
public void open(@PathParam("oid")
String orderId, Session session) {
sessionMap.put(orderId, session);
}
@OnClose
public void close(@PathParam("oid") String orderId) {
sessionMap.remove(orderId);
}
public static void sendMsg(String orderId, String msg) {
try {
Session session = sessionMap.get(orderId);
session.getBasicRemote().sendText(msg);
} catch (Exception e) {
e.printStackTrace();
}
}
}