IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 网络协议 -> Websocket 集群方案 -> 正文阅读

[网络协议]Websocket 集群方案

集群方案如下:

  1. 采用Redis的订阅与发布,由于Websocket无法被序列化,不能进行缓存,所以不能直接将websocket消息缓存到Redis中。
  2. 采用单纯的RabbitMQ,利用fanout\topic进行消息订阅,将Websocket消息结果发送到消息队列中,在进行转发接收。参考代码
  3. 采用RabbitMQ+MQTT消息协议,可以在RabbitMQ官网上看到
  4. 采用RabbitMQ+STOMP消息协议,可以在RabbitMQ官网上看到【推荐使用】

接下来介绍如何使用RabbitMQ+STOMP,代码如下

maven

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>


        <!--websocket 相关依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>webjars-locator-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>sockjs-client</artifactId>
            <version>1.0.2</version>
        </dependency>
        <dependency>
            <groupId>org.webjars</groupId>
            <artifactId>stomp-websocket</artifactId>
            <version>2.3.3</version>
        </dependency>

        <!--rabbitmq-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>


        <dependency>
        <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
        </dependency>

    </dependencies>

配置文件

spring:
  rabbitmq:
    host: 192.168.66.10
    port: 5672
    username: guest
    password: guest

RabbitMQ配置类

@Configuration
public class RabbitConfig {
 
    @Bean
    public Queue helloQueue() {
        return new Queue("hello");
    }
 
}

Websocket配置类


@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
 
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        /**
         * 配置简单的消息代理
         */
        config.enableSimpleBroker("/topic","/all");
 
        /**
         * 客户端发送过来的消息,需要以"/app"为前缀,再经过Broker转发给响应的Controller
         */
        config.setApplicationDestinationPrefixes("/app");
    }
 
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
 
        /**
         * 路径"/websocket"被注册为STOMP端点,对外暴露,客户端通过该路径接入WebSocket服务
         */
        registry.addEndpoint("/websocket").setAllowedOrigins("*").withSockJS();
    }
 
 
}

接收消息并发送

@CrossOrigin(allowCredentials = "true", allowedHeaders = "*")
@RestController
public class WebSocketTestController {
 
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

 

    //RequestMessage消息结果集
    @MessageMapping("/chat")
    public void messageHandling(RequestMessage requestMessage) throws Exception {
        String destination = "/topic/" + HtmlUtils.htmlEscape(requestMessage.getRoom());//htmlEscape  转换为HTML转义字符表示

        String content = HtmlUtils.htmlEscape(requestMessage.getContent());

 
        System.out.println( requestMessage.getRoom() );
        System.out.println( content );
 
 
      
 
        messagingTemplate.convertAndSend(destination, requestMessage);
    }
 
}

前端页面

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="UTF-8">
    <title>My WebSocket</title>

    <script src="js/sockjs.min.js"></script>
    <script src="js/jquery.min.js"></script>
    <script src="js/stomp.min.js"></script>
    <!--<script type="text/javascript"></script>-->

    <style>
        #message22{
            margin-top:40px;
            border:1px solid gray;
            padding:20px;
        }
    </style>

    <style>
        #message{
            margin-top:40px;
            border:1px solid gray;
            padding:20px;
        }
    </style>

</head>

<body>

频道号:<input id="room" type="text"/>
<button onclick="conectWebSocket()">连接WebSocket</button>
<button onclick="disconnect()">断开连接</button>
<hr />

<div id="message22"></div>


<br />
做题区:<input id="text" type="text" />
 频道号:<input id="toUser" type="text" />
<button onclick="sendMessage()">发送消息</button>
<div id="message"></div>
</body>

<script type="text/javascript">
    var stompClient;

    var serverUrl = "http://localhost:8080/websocket";

    var room;//频道号


    var websocket = null;

    //websocket连接
    function conectWebSocket(){

        this.room = document.getElementById('room').value;//频道号


        console.log(this.serverUrl);

        var socket = new SockJS(this.serverUrl);
        console.log(socket)
        this.stompClient = Stomp.over(socket);
        var that = this;
        this.stompClient.connect({}, function (frame) {
            //订阅消息
            that.stompClient.subscribe('/topic/'+that.room ,function(txt) {
                document.getElementById('message').innerHTML += JSON.parse(txt.body)['content']+ '<br/>';

            });
        });


    }

    //发送消息
    function sendMessage() {
        //获取输入的文本信息进行发送
        var message = document.getElementById('text').value;
        var room = document.getElementById('toUser').value;
        this.stompClient.send(
            '/app/chat',
            {},
            JSON.stringify({
                'room': room,
                'type': "1",//1,2
                'content': message,
                'userId':"566072523",//小明
                'questionId':"222299023",//题目1
                'createTime':"",
            })
        );

    }


    function disconnect() {

        //断开连接的方法
        if (this.stompClient !== undefined) {

            this.stompClient.disconnect();
            alert("Disconnected");
        }else{
            alert("当前没有连接websocket")
        }
        this.stompClient = undefined;

    }






</script>
</html>

  网络协议 最新文章
使用Easyswoole 搭建简单的Websoket服务
常见的数据通信方式有哪些?
Openssl 1024bit RSA算法---公私钥获取和处
HTTPS协议的密钥交换流程
《小白WEB安全入门》03. 漏洞篇
HttpRunner4.x 安装与使用
2021-07-04
手写RPC学习笔记
K8S高可用版本部署
mySQL计算IP地址范围
上一篇文章      下一篇文章      查看所有文章
加:2021-08-17 15:45:03  更:2021-08-17 15:46:33 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/17 16:44:27-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码