@SneakyThrows@GetMapping("/testSql")publicList<EntityDemo>testSql(String id){
/** WebSocket服务器的地址*/try{
Random random =newRandom();Integer i = random.nextInt(5)+1;CopyOnWriteArraySet<WebSocketServer> webSocketServerSet = webSocketServer.getWebSocketServer();for(WebSocketServer socketServer : webSocketServerSet){
if(socketServer.getSid().equals(i.toString())){
webSocketServer.close2(i.toString());returnnull;}}URI uri =newURI("ws://127.0.0.1:9088/test/websocket/"+ i);WebSocketContainer container =ContainerProvider.getWebSocketContainer();
container.connectToServer(myWebSocketClient, uri);
myWebSocketClient.sendMessage("你好"+ i);}catch(Exception e){
thrownewRuntimeException(e);}
log.info("++++++");returnnull;}
5: Note: The connection is automatically disconnected
After webSocket connection, I found a problem: if no data is transmitted every once in a while, the connection with the front end will be automatically disconnected. This problem can be solved by using heartbeat messages. For example, the client automatically sends a ping message to the server every 30 seconds, and the server returns pong.
5-1: Note: Objects cannot be automatically injected
Injecting objects using @Resource or @Autowired in classes annotated with @ServerEndpoint will fail and a null pointer exception will be reported. The solution is as follows:
The class annotated with @ServerEndpoint uses a static object and exposes the set method externally, so that it can be injected into WebSocketServer when the object is initialized.
There is a problem in distributed scenarios. When a request is loaded to the first server, the session is on the first server thread. The second request is loaded to the second server. At this time, the userId is used to find the current user's session, it cannot be found. I originally thought that by storing the session in redis, I can get the user's session from redis. I hope to use this method to solve the problem of message sending in distributed scenarios. This scenario can be solved by sending message middleware. The specific solution is as follows: every time you connect, the userId and the corresponding session are stored in the local machine. When sending a message, it is sent directly to MQ-Broker. Then each application load consumes the message. After getting the message, it determines On this machine, the session can be found based on the userId. If found, it will be pushed to the client.