对于需要实时的消息通信需要借助socket来进行消息传输
springboot集成websocket
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
@Slf4j
@ServerEndpoint("/websocket/getdata")
@Component
public class WebSocketServer {
private static int onlineCount = 0;
public static Map<String, Session> webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(Session session){
webSocketMap.put(session.getId(), session);
addOnlineCount();
log.info("开启websocket连接");
}
@OnClose
public void onClose(Session session){
webSocketMap.remove(session.getId());
subOnlineCount();
log.info("关闭websocketMap连接");
}
@OnMessage
public void onMessage(String message, Session session){
log.info("{}传来的消息为{}",session.getId(), message);
}
public void sendMessageToAll(String msg){
webSocketMap.forEach((id, session)->{
try {
session.getBasicRemote().sendText(msg);
log.info("消息发送成功{}", msg);
}catch (Exception e){
log.info("{},发送消息失败,原因{}",session.getId(),e);
}
});
}
private void subOnlineCount() {
WebSocketServer.onlineCount--;
}
private void addOnlineCount() {
WebSocketServer.onlineCount++;
}
}
使用WebSocket中出现的问题
- 问题:
javax.servlet.ServletException: javax.websocket.DeploymentException: The path [webSocket] is not valid.
解决@ServerEndpoint("/websocket/getdata") 路径开头要有/
WebSocketConfig 类中注解错误使用成@Configurable ,应该为:@Configuration 。
|