springboot+websocket+redis搭建的實(shí)現(xiàn)
在多負(fù)載環(huán)境下使用websocket。
一、原因
在某些業(yè)務(wù)場(chǎng)景,我們需要頁面對(duì)于后臺(tái)的操作進(jìn)行實(shí)時(shí)的刷新,這時(shí)候就需要使用websocket。
通常在后臺(tái)單機(jī)的情況下沒有任何的問題,如果后臺(tái)經(jīng)過nginx等進(jìn)行負(fù)載的話,則會(huì)導(dǎo)致前臺(tái)不能準(zhǔn)備的接收到后臺(tái)給與的響應(yīng)。socket屬于長連接,其session只會(huì)保存在一臺(tái)服務(wù)器上,其他負(fù)載及其不會(huì)持有這個(gè)session,此時(shí),我們需要使用redis的發(fā)布訂閱來實(shí)現(xiàn),session的共享。
二、環(huán)境準(zhǔn)備
在https://mvnrepository.com/里,查找websocket的依賴。使用springboot的starter依賴,注意對(duì)應(yīng)自己springboot的版本。
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.2.10.RELEASE</version> </dependency>
除此之外添加redis的依賴,也使用starter版本:
<!-- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
三、代碼
redis監(jiān)聽配置:
/** * @description: redis監(jiān)聽配置類 * @author:weirx * @date:2021/3/22 14:08 * @version:3.0 */ @Configuration public class RedisConfig { /** * description: 手動(dòng)注冊(cè)Redis監(jiān)聽到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配置:
/** * @description: websocket配置類 * @author:weirx * @date:2021/3/22 14:11 * @version:3.0 */ @Configuration public class WebSocketConfig { /** * description: 這個(gè)配置類的作用是要注入ServerEndpointExporter, * 這個(gè)bean會(huì)自動(dòng)注冊(cè)使用了@ServerEndpoint注解聲明的Websocket endpoint。 * 如果是使用獨(dú)立的servlet容器,而不是直接使用springboot的內(nèi)置容器, * 就不要注入ServerEndpointExporter,因?yàn)樗鼘⒂扇萜髯约禾峁┖凸芾怼? * * @return: org.springframework.web.socket.server.standard.ServerEndpointExporter * @author: weirx * @time: 2021/3/22 14:12 */ @Bean public ServerEndpointExporter serverEndpointExporter(){ return new ServerEndpointExporter(); } }
redis工具類:
@Component public class RedisUtil { @Autowired private StringRedisTemplate stringRedisTemplate; /** * 發(fā)布 * * @param key */ public void publish(String key, String value) { stringRedisTemplate.convertAndSend(key, value); } }
WebSocket服務(wù)提供類:
/** * description: @ServerEndpoint 注解是一個(gè)類層次的注解, * 它的功能主要是將目前的類定義成一個(gè)websocket服務(wù)器端,注解的值將被用于監(jiān)聽用戶連接的終端訪問URL地址, * 客戶端可以通過這個(gè)URL來連接到WebSocket服務(wù)器端使用springboot的唯一區(qū)別是要@Component聲明下, * 而使用獨(dú)立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。 * * @author: weirx * @time: 2021/3/22 14:31 */ @Slf4j @Component @ServerEndpoint("/websocket/server/{loginName}") public class WebSocketServer { /** * 因?yàn)锧ServerEndpoint不支持注入,所以使用SpringUtils獲取IOC實(shí)例 */ private RedisMessageListenerContainer redisMessageListenerContainer = ApplicationContextProvider.getBean(RedisMessageListenerContainer.class); /** * 靜態(tài)變量,用來記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。 */ private static AtomicInteger onlineCount = new AtomicInteger(0); /** * concurrent包的線程安全Set,用來存放每個(gè)客戶端對(duì)應(yīng)的webSocket對(duì)象。 * 若要實(shí)現(xiàn)服務(wù)端與單一客戶端通信的話,可以使用Map來存放,其中Key可以為用戶標(biāo)識(shí) */ private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); /** * 與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù) */ private Session session; /** * redis監(jiān)聽 */ private SubscribeListener subscribeListener; /** * 連接建立成功調(diào)用的方法 * * @param session 可選的參數(shù)。session為與某個(gè)客戶端的連接會(huì)話,需要通過它來給客戶端發(fā)送數(shù)據(jù) */ @OnOpen public void onOpen(@PathParam("loginName") String loginName, Session session) { this.session = session; //加入set中 webSocketSet.add(this); //在線數(shù)加1 addOnlineCount(); log.info("有新連接[" + loginName + "]加入!當(dāng)前在線人數(shù)為{}", getOnlineCount()); subscribeListener = new SubscribeListener(); subscribeListener.setSession(session); //設(shè)置訂閱topic redisMessageListenerContainer.addMessageListener( subscribeListener, new ChannelTopic(Constants.TOPIC_PREFIX + loginName)); } /** * 連接關(guān)閉調(diào)用的方法 */ @OnClose public void onClose() throws IOException { //從set中刪除 webSocketSet.remove(this); //在線數(shù)減1 subOnlineCount(); redisMessageListenerContainer.removeMessageListener(subscribeListener); log.info("有一連接關(guān)閉!當(dāng)前在線人數(shù)為{}", getOnlineCount()); } /** * 收到客戶端消息后調(diào)用的方法 * * @param message 客戶端發(fā)送過來的消息 * @param session 可選的參數(shù) */ @OnMessage public void onMessage(String message, Session session) { log.info("來自客戶端的消息:{}", message); //群發(fā)消息 for (WebSocketServer item : webSocketSet) { try { item.sendMessage(message); } catch (IOException e) { log.info("發(fā)送消息異常:msg = {}", e); continue; } } } /** * 發(fā)生錯(cuò)誤時(shí)調(diào)用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.info("發(fā)生錯(cuò)誤,{}", error); } /** * 這個(gè)方法與上面幾個(gè)方法不一樣。沒有用注解,是根據(jù)自己需要添加的方法。 * * @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消息發(fā)布:
@Autowired private RedisUtil redisUtil; @Override public Result send(String loginName, String msg) { //推送站內(nèi)信webSocket redisUtil.publish("TOPIC" + loginName, msg); return Result.success(); }
前端vue代碼:
<template> <div class="dashboard-container"> <div class="dashboard-text">消息內(nèi)容: {{ responseData }}</div> </div> </template> <script> import {mapGetters} from 'vuex' export default { data() { return { websocket: null, responseData: null } }, created() { this.initWebSocket(); }, destroyed() { this.websock.close() //離開路由之后斷開websocket連接 }, methods: { //初始化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() { //連接建立之后執(zhí)行send方法發(fā)送數(shù)據(jù) let actions = {"用戶賬號(hào)": "admin"}; this.websocketsend(JSON.stringify(actions)); }, websocketonerror() {//連接建立失敗重連 this.initWebSocket(); }, websocketonmessage(e) { //數(shù)據(jù)接收 const redata = JSON.parse(e.data); this.responseData = redata; }, websocketsend(Data) {//數(shù)據(jù)發(fā)送 this.websock.send(Data); }, websocketclose(e) { //關(guān)閉 console.log('斷開連接', e); }, }, name: 'Dashboard', computed: { ...mapGetters([ 'name', 'roles' ]) } } </script>
四、測(cè)試
發(fā)送前
發(fā)送后
到此這篇關(guān)于springboot+websocket+redis搭建的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)springboot websocket redis搭建內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java開源項(xiàng)目jeecgboot的超詳細(xì)解析
JeecgBoot是一款基于BPM的低代碼平臺(tái),下面這篇文章主要給大家介紹了關(guān)于java開源項(xiàng)目jeecgboot的相關(guān)資料,文中通過圖文以及實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-10-10詳解Spring Boot中如何自定義SpringMVC配置
這篇文章主要給大家介紹了關(guān)于Spring Boot中如何自定義SpringMVC配置的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-09-09Javaweb動(dòng)態(tài)開發(fā)最重要的Servlet詳解
動(dòng)態(tài)web的核心是Servlet,由tomcat解析并執(zhí)行,本質(zhì)是Java中的一個(gè)類(面向?qū)ο螅┻@個(gè)類的功能十分強(qiáng)大幾乎可以完成全部功能,在Java規(guī)范中只有Servlet實(shí)現(xiàn)類實(shí)例化的對(duì)象才能被瀏覽器訪問,所以掌握Servlet具有重要意義2022-08-08Spring?Cloud?Gateway編碼實(shí)現(xiàn)任意地址跳轉(zhuǎn)
這篇文章主要介紹了Spring?Cloud?Gateway編碼實(shí)現(xiàn)任意地址跳轉(zhuǎn)的相關(guān)資料,需要的朋友可以參考下2023-06-06Spring事務(wù)管理中關(guān)于數(shù)據(jù)庫連接池詳解
事務(wù)的作用就是為了保證用戶的每一個(gè)操作都是可靠的,事務(wù)中的每一步操作都必須成功執(zhí)行,只要有發(fā)生異常就 回退到事務(wù)開始未進(jìn)行操作的狀態(tài)。事務(wù)管理是Spring框架中最為常用的功能之一,我們?cè)谑褂肧pring Boot開發(fā)應(yīng)用時(shí),大部分情況下也都需要使用事務(wù)2022-12-12SpringMVC中Controller類數(shù)據(jù)響應(yīng)的方法
這篇文章主要介紹了SpringMVC中的數(shù)據(jù)響應(yīng)的問題,主要來了解 Controller 類如何進(jìn)行數(shù)據(jù)響應(yīng)的,本文給大家介紹的非常詳細(xì),需要的朋友可以參考下2021-07-07