springboot+websocket+redis搭建的實現
在多負載環境下使用websocket。
一、原因在某些業務場景,我們需要頁面對于后臺的操作進行實時的刷新,這時候就需要使用websocket。
通常在后臺單機的情況下沒有任何的問題,如果后臺經過nginx等進行負載的話,則會導致前臺不能準備的接收到后臺給與的響應。socket屬于長連接,其session只會保存在一臺服務器上,其他負載及其不會持有這個session,此時,我們需要使用redis的發布訂閱來實現,session的共享。
二、環境準備在https://mvnrepository.com/里,查找websocket的依賴。使用springboot的starter依賴,注意對應自己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監聽配置:
/** * @description: redis監聽配置類 * @author:weirx * @date:2021/3/22 14:08 * @version:3.0 */@Configurationpublic class RedisConfig { /** * description: 手動注冊Redis監聽到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 */@Configurationpublic class WebSocketConfig { /** * description: 這個配置類的作用是要注入ServerEndpointExporter, * 這個bean會自動注冊使用了@ServerEndpoint注解聲明的Websocket endpoint。 * 如果是使用獨立的servlet容器,而不是直接使用springboot的內置容器, * 就不要注入ServerEndpointExporter,因為它將由容器自己提供和管理。 * * @return: org.springframework.web.socket.server.standard.ServerEndpointExporter * @author: weirx * @time: 2021/3/22 14:12 */ @Bean public ServerEndpointExporter serverEndpointExporter(){return new ServerEndpointExporter(); }}
redis工具類:
@Componentpublic class RedisUtil { @Autowired private StringRedisTemplate stringRedisTemplate; /** * 發布 * * @param key */ public void publish(String key, String value) {stringRedisTemplate.convertAndSend(key, value); }}
WebSocket服務提供類:
/** * description: @ServerEndpoint 注解是一個類層次的注解, * 它的功能主要是將目前的類定義成一個websocket服務器端,注解的值將被用于監聽用戶連接的終端訪問URL地址, * 客戶端可以通過這個URL來連接到WebSocket服務器端使用springboot的唯一區別是要@Component聲明下, * 而使用獨立容器是由容器自己管理websocket的,但在springboot中連容器都是spring管理的。 * * @author: weirx * @time: 2021/3/22 14:31 */@Slf4j@Component@ServerEndpoint('/websocket/server/{loginName}')public class WebSocketServer { /** * 因為@ServerEndpoint不支持注入,所以使用SpringUtils獲取IOC實例 */ private RedisMessageListenerContainer redisMessageListenerContainer = ApplicationContextProvider.getBean(RedisMessageListenerContainer.class); /** * 靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。 */ private static AtomicInteger onlineCount = new AtomicInteger(0); /** * concurrent包的線程安全Set,用來存放每個客戶端對應的webSocket對象。 * 若要實現服務端與單一客戶端通信的話,可以使用Map來存放,其中Key可以為用戶標識 */ private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>(); /** * 與某個客戶端的連接會話,需要通過它來給客戶端發送數據 */ private Session session; /** * redis監聽 */ private SubscribeListener subscribeListener; /** * 連接建立成功調用的方法 * * @param session 可選的參數。session為與某個客戶端的連接會話,需要通過它來給客戶端發送數據 */ @OnOpen public void onOpen(@PathParam('loginName') String loginName, Session session) {this.session = session;//加入set中webSocketSet.add(this);//在線數加1addOnlineCount();log.info('有新連接[' + loginName + ']加入!當前在線人數為{}', getOnlineCount());subscribeListener = new SubscribeListener();subscribeListener.setSession(session);//設置訂閱topicredisMessageListenerContainer.addMessageListener(subscribeListener, new ChannelTopic(Constants.TOPIC_PREFIX + loginName)); } /** * 連接關閉調用的方法 */ @OnClose public void onClose() throws IOException {//從set中刪除webSocketSet.remove(this);//在線數減1subOnlineCount();redisMessageListenerContainer.removeMessageListener(subscribeListener);log.info('有一連接關閉!當前在線人數為{}', getOnlineCount()); } /** * 收到客戶端消息后調用的方法 * * @param message 客戶端發送過來的消息 * @param session 可選的參數 */ @OnMessage public void onMessage(String message, Session session) {log.info('來自客戶端的消息:{}', message);//群發消息for (WebSocketServer item : webSocketSet) { try {item.sendMessage(message); } catch (IOException e) {log.info('發送消息異常:msg = {}', e);continue; }} } /** * 發生錯誤時調用 * * @param session * @param error */ @OnError public void onError(Session session, Throwable error) {log.info('發生錯誤,{}', error); } /** * 這個方法與上面幾個方法不一樣。沒有用注解,是根據自己需要添加的方法。 * * @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消息發布:
@Autowired private RedisUtil redisUtil; @Override public Result send(String loginName, String msg) {//推送站內信webSocketredisUtil.publish('TOPIC' + loginName, msg);return Result.success(); }
前端vue代碼:
<template> <div class='dashboard-container'> <div class='dashboard-text'>消息內容: {{ 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() { //連接建立之后執行send方法發送數據let actions = {'用戶賬號': 'admin'};this.websocketsend(JSON.stringify(actions)); }, websocketonerror() {//連接建立失敗重連this.initWebSocket(); }, websocketonmessage(e) { //數據接收const redata = JSON.parse(e.data);this.responseData = redata; }, websocketsend(Data) {//數據發送this.websock.send(Data); }, websocketclose(e) { //關閉console.log(’斷開連接’, e); }, }, name: ’Dashboard’, computed: { ...mapGetters([’name’,’roles’ ]) } }</script>四、測試
發送前
發送后
到此這篇關于springboot+websocket+redis搭建的實現的文章就介紹到這了,更多相關springboot websocket redis搭建內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!
相關文章: