Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build springboot websocket redis

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to build springboot websocket redis". Friends who are interested might as well take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to build springboot websocket redis.

First, reasons

In some business scenarios, we need the page to refresh the background operation in real time, so we need to use websocket.

There is usually no problem in the case of a stand-alone machine in the background. if the background is loaded through nginx, it will cause the foreground to receive the response from the background unprepared. Socket is a persistent connection, its session will only be stored on one server, other loads and will not hold the session, in this case, we need to use redis's publish subscription to achieve session sharing.

II. Environmental preparation

In https://mvnrepository.com/, look for websocket dependencies. Using springboot's starter dependency, pay attention to the version of your own springboot.

Org.springframework.boot spring-boot-starter-websocket 2.2.10.RELEASE

In addition to adding redis dependencies, you also use the starter version:

Org.springframework.boot spring-boot-starter-data-redis III. Code

Redis snooping configuration:

/ * @ description: redis snooping configuration class * @ author:weirx * @ date:2021/3/22 14:08 * @ version:3.0 * / @ Configurationpublic class RedisConfig {/ * description: manually register Redis to listen to IOC * * @ param redisConnectionFactory * @ return: org.springframework.data.redis.listener.RedisMessageListenerContainer * @ author:weirx * @ time: 2021-3-22 14:11 * / @ Bean public RedisMessageListenerContainer redisMessageListenerContainer (RedisConnectionFactory redisConnectionFactory) {RedisMessageListenerContainer container = new RedisMessageListenerContainer () Container.setConnectionFactory (redisConnectionFactory); return container;}}

WebSocket configuration:

/ * * @ description: websocket configuration class * @ author:weirx * @ date:2021/3/22 14:11 * @ version:3.0 * / @ Configurationpublic class WebSocketConfig {/ * description: this configuration class is used to inject ServerEndpointExporter. * this bean automatically registers the Websocket endpoint declared with the @ ServerEndpoint annotation. * if you are using a separate servlet container instead of directly using springboot's built-in container, * do not inject ServerEndpointExporter, as it will be provided and managed by the container itself. * * @ return: org.springframework.web.socket.server.standard.ServerEndpointExporter * @ author: weirx * @ time: 14:12 on 2021-3-22 * / @ Bean public ServerEndpointExporter serverEndpointExporter () {return new ServerEndpointExporter ();}}

Redis utility class:

@ Componentpublic class RedisUtil {@ Autowired private StringRedisTemplate stringRedisTemplate; / * publish * * @ param key * / public void publish (String key, String value) {stringRedisTemplate.convertAndSend (key, value);}}

WebSocket service provider class:

/ * * description: @ ServerEndpoint annotation is a class-level annotation. * its main function is to define the current class as a websocket server. The value of the annotation will be used to listen for the terminal access URL address of the user connection. * the client can connect to the WebSocket server through this URL. The only difference in using springboot is under the @ Component declaration, * while using an independent container is managed by the container itself. But in springboot, even containers are managed by spring. * * @ author: weirx * @ time: 14:31 on 2021-3-22 * / @ Slf4j@Component@ServerEndpoint ("/ websocket/server/ {loginName}") public class WebSocketServer {/ * because @ ServerEndpoint does not support injection, use SpringUtils to obtain the IOC instance * / private RedisMessageListenerContainer redisMessageListenerContainer = ApplicationContextProvider.getBean (RedisMessageListenerContainer.class); / * static variable, which is used to record the current number of online connections. It should be designed to be thread safe. * / private static AtomicInteger onlineCount = new AtomicInteger (0); / * the thread-safe Set of the concurrent package is used to store the webSocket object corresponding to each client. * to enable the server to communicate with a single client, you can use Map to store it, where Key can identify * / private static CopyOnWriteArraySet webSocketSet = new CopyOnWriteArraySet () for the user; / * the connection session with a client needs to send data to the client through it * / private Session session; / * * redis snooping * / private SubscribeListener subscribeListener / * connection establishes an optional parameter for the method called successfully * * @ param session. Session is a connection session with a client. You need it to send data * / @ OnOpen public void onOpen (@ PathParam ("loginName") String loginName, Session session) {this.session = session; / / add webSocketSet.add (this) to set; / / number of online plus 1 addOnlineCount (); log.info ("New connection [" + loginName + "] join! Current number of online users is {} ", getOnlineCount (); subscribeListener = new SubscribeListener (); subscribeListener.setSession (session); / / set subscription topic redisMessageListenerContainer.addMessageListener (subscribeListener, new ChannelTopic (Constants.TOPIC_PREFIX + loginName)) } / * connection close method * / @ OnClose public void onClose () throws IOException {/ / remove webSocketSet.remove (this) from set; / / the number of lines minus 1 subOnlineCount (); redisMessageListenerContainer.removeMessageListener (subscribeListener); log.info ("A connection is closed! The current number of online users is {} ", getOnlineCount ();} / * the method called after receiving the client message * * @ param message client sent message * @ param session optional parameter * / @ OnMessage public void onMessage (String message, Session session) {log.info (" message from client: {} ", message) / / for (WebSocketServer item: webSocketSet) {try {item.sendMessage (message);} catch (IOException e) {log.info ("send message exception: msg = {}", e); continue When an error occurs, call * * @ param session * @ param error * / @ OnError public void onError (Session session, Throwable error) {log.info ("error occurs, {}", error);} / * * this method is different from the above methods. Do not use annotations, but add methods according to your own needs. * * @ param message * @ throws IOException * / public void sendMessage (String message) throws IOException {this.session.getBasicRemote () .sendText (message);} public int getOnlineCount () {return onlineCount.get ();} public void addOnlineCount () {WebSocketServer.onlineCount.getAndIncrement ();} public void subOnlineCount () {WebSocketServer.onlineCount.getAndDecrement ();}}

Redis message release:

@ Autowired private RedisUtil redisUtil; @ Override public Result send (String loginName, String msg) {/ / push webSocket redisUtil.publish ("TOPIC" + loginName, msg); return Result.success ();}

Front-end vue code:

Message content: {{responseData}} import {mapGetters} from 'vuex' export default {data () {return {websocket: null, responseData: null}}, created () {this.initWebSocket () }, destroyed () {this.websock.close () / / disconnect the websocket connection after leaving the route}, methods: {/ / initialize websocket initWebSocket () {const wsUri = "ws://127.0.0.1:21116/websocket/server/" + "admin"; this.websock = new WebSocket (wsUri); this.websock.onmessage = this.websocketonmessage This.websock.onopen = this.websocketonopen; this.websock.onerror = this.websocketonerror; this.websock.onclose = this.websocketclose;}, websocketonopen () {/ / execute the send method to send data after the connection is established let actions = {"user account": "admin"}; this.websocketsend (JSON.stringify (actions)) }, websocketonerror () {/ / connection failed to reconnect this.initWebSocket ();}, websocketonmessage (e) {/ / data receive const redata = JSON.parse (e.data); this.responseData = redata;}, websocketsend (Data) {/ / data send this.websock.send (Data) }, websocketclose (e) {/ / close console.log ('disconnect', e);},}, name: 'Dashboard', computed: {. MapGetters ([' name', 'roles'])}} so far, I believe you have a better understanding of "how to build springboot websocket redis". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report