About what is websocket and why to use websocket I will not describe here, can look at the answer on Zhihu websocket is what principle

Ok, let’s get right to the subject: gracefully communicating with WebSockets in Springboot

1. Understand the requirements

For example, we now have a requirement: the station message automatically refresh 1. Who sends the message? In our system, each user’s actions send a message to the corresponding handler. 2. Who handles messages? The corresponding handler may or may not be the sender of the message, so the system needs to actively tell the corresponding handler that something needs to be done, rather than each handler refreshing the interface all the time.

Two, the realization of the concept of design

In the above requirement we can see that the implementation is very simple, we can add a section of code after the user operation to send a Websocket notification, but this is really good, if only one or two places, but if we have dozens of places to push messages to the front end? Some say you can write a utility method that the business code calls. Yes, you can do that, but I don’t think it’s elegant. Why? This would cause our business code to be hacked, undermining the method’s single responsibility. At this point, we think, since it is business code that needs to send message notifications after invocation, THEN AOP, yes, is AOP. We can define an aspect and then enhance our business methods within the aspect. Without further ado, here are the blueprints:How to use WebSocket in SpringbootSpringboot uses websocketsAbstractWebSocketServer—- >AbstractWebSocketServer—–> laihua number (number of laihua) (number of laihua) (number of laihua) (number of laihua) An aspect, we just need to put this annotation on top of the business method, the business method will be enhanced by the aspect and now we need to connect the left and right sides. So how does the right hand side tell the left hand side to push messages to the client? Here we use a broadcast message queue from Redis, which you can refer to in this articleImplement RabbitMq message broadcast with RedisWe will call a message sending method in the section to tell the websocket on the left to push the message

Three, code implementation

WebsocketServer interface: CusstomSession

AbstractWebsocketServer:

Implementation subclass:Section method of section class:

How to use 1, back-end call without invading the business code, just add an annotation can achieve message notification2. Front-end call:

Five, the conclusion

In this implementation because of the use of Redis message broadcast, so it is suitable for distributed systems, in distributed scenarios, the client only need to register any node.