springboot集成websocket
1、引入jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2、创建config类
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
3、定义websocket服务
@Slf4j
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketService {
private static WarningService warningService;
@Autowired
public void setChatService(WarningService warningService) {
WebSocketService.warningService = warningService;
}
private static final ConcurrentHashMap<String, Session> webSocketMap = new ConcurrentHashMap<>();
@OnOpen
public void onOpen(@PathParam(value = "userId") String userId, Session session) {
webSocketMap.put(userId, session);
log.info("【websocket消息】有新的连接, 总数: " + webSocketMap.size() + " 用户id: " + userId);
warningService.onOpenByAlert(userId);
}
@OnClose
public void onClose(@PathParam(value = "userId") String userId, Session session) {
webSocketMap.remove(userId);
log.info("【websocket消息】连接断开, 总数: " + webSocketMap.size() + " 用户id已离开: " + userId);
}
@OnMessage
public void onMessage(@PathParam(value = "userId") String userId, String message) {
log.info("【websocket消息】收到客户端用户 " + userId + " 发来的消息" + message);
if ("ping".equals(message)) {
sendMessage(userId, "received");
} else {
warningService.onMessageAlert(userId, message);
}
}
@OnError
public void onError(Session session, Throwable error) {
log.info("【websocket消息】收到客户端用户发生错误");
error.printStackTrace();
}
public void sendMessage(String userId, String message) {
try {
if (webSocketMap.get(userId) != null) {
sendMessage(webSocketMap.get(userId), message);
log.info("【websocket消息】向客户端用户 " + userId + "发送消息成功-" + message);
} else {
log.info("【websocket消息】向客户端用户 " + userId + "发送消息失败,用户已离线");
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(Session session, String message) throws IOException {
session.getAsyncRemote().sendText(message);
}
}
4、直接调用发送消息
new WebSocketService().sendMessage(userId, "你好!123");
5、客户端连接
请求地址:ws://192.168.0.141:8089/websocket/123
6、部署到服务器
如果配置了nginx会链接失败,
在nginx配置文件 location 里加入下边代码,在重启nginx即可
# 增加Upgrade协议头和Connection协议头,使http连接升级到websocket连接
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";