最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot+websocket+redis搭建的實(shí)現(xiàn)

 更新時(shí)間:2021年04月09日 11:33:22   作者:我犟不過(guò)你  
這篇文章主要介紹了springboot+websocket+redis搭建的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

在多負(fù)載環(huán)境下使用websocket。

一、原因

在某些業(yè)務(wù)場(chǎng)景,我們需要頁(yè)面對(duì)于后臺(tái)的操作進(jìn)行實(shí)時(shí)的刷新,這時(shí)候就需要使用websocket。

通常在后臺(tái)單機(jī)的情況下沒(méi)有任何的問(wèn)題,如果后臺(tái)經(jīng)過(guò)nginx等進(jìn)行負(fù)載的話(huà),則會(huì)導(dǎo)致前臺(tái)不能準(zhǔn)備的接收到后臺(tái)給與的響應(yīng)。socket屬于長(zhǎng)連接,其session只會(huì)保存在一臺(tái)服務(wù)器上,其他負(fù)載及其不會(huì)持有這個(gè)session,此時(shí),我們需要使用redis的發(fā)布訂閱來(lái)實(shí)現(xiàn),session的共享。

二、環(huán)境準(zhǔn)備

https://mvnrepository.com/里,查找websocket的依賴(lài)。使用springboot的starter依賴(lài),注意對(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的依賴(lài),也使用starter版本:

        <!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

三、代碼

redis監(jiān)聽(tīng)配置:

/**
 * @description: redis監(jiān)聽(tīng)配置類(lèi)
 * @author:weirx
 * @date:2021/3/22 14:08
 * @version:3.0
 */
@Configuration
public class RedisConfig {

    /**
     * description: 手動(dòng)注冊(cè)Redis監(jiān)聽(tīng)到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配置類(lèi)
 * @author:weirx
 * @date:2021/3/22 14:11
 * @version:3.0
 */
@Configuration
public class WebSocketConfig {

    /**
     * description: 這個(gè)配置類(lèi)的作用是要注入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工具類(lèi):

@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 發(fā)布
     *
     * @param key
     */
    public void publish(String key, String value) {
        stringRedisTemplate.convertAndSend(key, value);
    }
}

WebSocket服務(wù)提供類(lèi):

/**
 * description: @ServerEndpoint 注解是一個(gè)類(lèi)層次的注解,
 * 它的功能主要是將目前的類(lèi)定義成一個(gè)websocket服務(wù)器端,注解的值將被用于監(jiān)聽(tīng)用戶(hù)連接的終端訪(fǎng)問(wèn)URL地址,
 * 客戶(hù)端可以通過(guò)這個(gè)URL來(lái)連接到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)變量,用來(lái)記錄當(dāng)前在線(xiàn)連接數(shù)。應(yīng)該把它設(shè)計(jì)成線(xiàn)程安全的。
     */
    private static AtomicInteger onlineCount = new AtomicInteger(0);

    /**
     * concurrent包的線(xiàn)程安全Set,用來(lái)存放每個(gè)客戶(hù)端對(duì)應(yīng)的webSocket對(duì)象。
     * 若要實(shí)現(xiàn)服務(wù)端與單一客戶(hù)端通信的話(huà),可以使用Map來(lái)存放,其中Key可以為用戶(hù)標(biāo)識(shí)
     */
    private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();

    /**
     * 與某個(gè)客戶(hù)端的連接會(huì)話(huà),需要通過(guò)它來(lái)給客戶(hù)端發(fā)送數(shù)據(jù)
     */
    private Session session;

    /**
     * redis監(jiān)聽(tīng)
     */
    private SubscribeListener subscribeListener;

    /**
     * 連接建立成功調(diào)用的方法
     *
     * @param session 可選的參數(shù)。session為與某個(gè)客戶(hù)端的連接會(huì)話(huà),需要通過(guò)它來(lái)給客戶(hù)端發(fā)送數(shù)據(jù)
     */
    @OnOpen
    public void onOpen(@PathParam("loginName") String loginName, Session session) {
        this.session = session;
        //加入set中
        webSocketSet.add(this);
        //在線(xiàn)數(shù)加1
        addOnlineCount();
        log.info("有新連接[" + loginName + "]加入!當(dāng)前在線(xiàn)人數(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);
        //在線(xiàn)數(shù)減1
        subOnlineCount();
        redisMessageListenerContainer.removeMessageListener(subscribeListener);
        log.info("有一連接關(guān)閉!當(dāng)前在線(xiàn)人數(shù)為{}", getOnlineCount());
    }

    /**
     * 收到客戶(hù)端消息后調(diào)用的方法
     *
     * @param message 客戶(hù)端發(fā)送過(guò)來(lái)的消息
     * @param session 可選的參數(shù)
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("來(lái)自客戶(hù)端的消息:{}", 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è)方法不一樣。沒(méi)有用注解,是根據(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() //離開(kāi)路由之后斷開(kāi)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ù)賬號(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('斷開(kāi)連接', 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)文章

  • 揭秘SpringBoot!一分鐘教你實(shí)現(xiàn)配置的動(dòng)態(tài)神刷新

    揭秘SpringBoot!一分鐘教你實(shí)現(xiàn)配置的動(dòng)態(tài)神刷新

    在今天的指南中,我們將深入探索SpringBoot?動(dòng)態(tài)刷新的強(qiáng)大功能,讓你的應(yīng)用保持最新鮮的狀態(tài),想象一下,無(wú)需重啟,你的應(yīng)用就能實(shí)時(shí)更新配置,是不是很酷?跟我一起,讓我們揭開(kāi)這項(xiàng)技術(shù)如何讓開(kāi)發(fā)變得更加靈活和高效的秘密吧!
    2024-03-03
  • 關(guān)于JSqlparser使用攻略(高效的SQL解析工具)

    關(guān)于JSqlparser使用攻略(高效的SQL解析工具)

    這篇文章主要介紹了關(guān)于JSqlparser使用攻略(高效的SQL解析工具),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • SpringMVC核心技術(shù)

    SpringMVC核心技術(shù)

    這篇文章主要介紹了SpringMVC入門(mén)實(shí)例,在springmvc入門(mén)教程里算是比較不錯(cuò)的,結(jié)構(gòu)也比較完整,需要的朋友可以參考。希望可以幫助到你
    2021-07-07
  • 子線(xiàn)程任務(wù)發(fā)生異常時(shí)主線(xiàn)程事務(wù)回滾示例過(guò)程

    子線(xiàn)程任務(wù)發(fā)生異常時(shí)主線(xiàn)程事務(wù)回滾示例過(guò)程

    這篇文章主要為大家介紹了子線(xiàn)程任務(wù)發(fā)生了異常時(shí)主線(xiàn)程事務(wù)如何回滾的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-03-03
  • Idea創(chuàng)建springboot不能選擇java8的解決

    Idea創(chuàng)建springboot不能選擇java8的解決

    在IDEA 2023版本創(chuàng)建Spring Boot項(xiàng)目時(shí),發(fā)現(xiàn)沒(méi)有Java 8選項(xiàng),只有Java 17和Java 20,解決方法包括:通過(guò)修改服務(wù)器URL(推薦)或直接在創(chuàng)建后修改pom.xml文件中的Spring Boot和Java版本
    2025-01-01
  • SpringBoot整合EasyExcel進(jìn)行大數(shù)據(jù)處理的方法詳解

    SpringBoot整合EasyExcel進(jìn)行大數(shù)據(jù)處理的方法詳解

    EasyExcel是一個(gè)基于Java的簡(jiǎn)單、省內(nèi)存的讀寫(xiě)Excel的開(kāi)源項(xiàng)目。在盡可能節(jié)約內(nèi)存的情況下支持讀寫(xiě)百M(fèi)的Excel。本文將在SpringBoot中整合EasyExcel進(jìn)行大數(shù)據(jù)處理,感興趣的可以了解一下
    2022-05-05
  • SpringBoot整合FastDFS方法過(guò)程詳解

    SpringBoot整合FastDFS方法過(guò)程詳解

    這篇文章主要介紹了SpringBoot整合FastDFS方法過(guò)程詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-05-05
  • Java中的Graphics2D類(lèi)基本使用教程

    Java中的Graphics2D類(lèi)基本使用教程

    這篇文章主要介紹了Java中的Graphics2D類(lèi)基本使用教程,Graphics2D類(lèi)較之Graphics類(lèi)中的功能更加專(zhuān)業(yè),需要的朋友可以參考下
    2015-10-10
  • 詳解如何在低版本的Spring中快速實(shí)現(xiàn)類(lèi)似自動(dòng)配置的功能

    詳解如何在低版本的Spring中快速實(shí)現(xiàn)類(lèi)似自動(dòng)配置的功能

    這篇文章主要介紹了詳解如何在低版本的Spring中快速實(shí)現(xiàn)類(lèi)似自動(dòng)配置的功能,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2019-05-05
  • 基于SpringBoot應(yīng)用監(jiān)控Actuator安全隱患及解決方式

    基于SpringBoot應(yīng)用監(jiān)控Actuator安全隱患及解決方式

    這篇文章主要介紹了SpringBoot應(yīng)用監(jiān)控Actuator安全隱患及解決方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07

最新評(píng)論

元江| 舞阳县| 宁乡县| 大安市| 临沂市| 宜都市| 贵德县| 柳林县| 客服| 汾阳市| 抚顺市| 池州市| 娄底市| 临海市| 尉氏县| 宝山区| 明水县| 东乌珠穆沁旗| 韶关市| 长汀县| 弋阳县| 枣庄市| 江华| 红桥区| 乳山市| 尖扎县| 东山县| 渝中区| 祁东县| 交城县| 兴安县| 如东县| 庄浪县| 贵溪市| 泸西县| 荔浦县| 滦南县| 泗洪县| 天津市| 杨浦区| 十堰市|