springboot整合websocket实现服务器主动推送消息到客户端(点对点)

原文:https://www.cnblogs.com/hhhshct/p/8849449.html      

   服务器端推送技术在web开发中比较常用,可能早期很多人的解决方案是采用ajax向服务器轮询消息,这种方式的轮询频率不好控制,所以大大增加了服务器的压力,后来有了下面的方案:当客户端向服务器发送请求时,服务器端会抓住这个请求不放,等有数据更新的时候才返回给客户端,当客户端接收到数据后再次发送请求,周而复始,这样就大大减少了请求次数,减轻了服务器的压力,当前主要有SSE(Server Send Event 服务器端事件发送)的服务器端推送和基于Servlet3.0+异步方法特性实现的服务器端推送。而本次我将利用webSokcet实现服务器端消息推送。

1.新建springboot项目,pom.xml中加入:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

2、WebSocketConfig

package com.jp.mall.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;


@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/topic","/user");//topic用来广播,user用来实现p2p
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/webServer").withSockJS();
        registry.addEndpoint("/queueServer").withSockJS();//注册两个STOMP的endpoint,分别用于广播和点对点
    }
}

3.WsController

package com.example.wwbsocket;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

@Controller
public class WsController {

    @Autowired
    public SimpMessagingTemplate template;

    @MessageMapping("/queue")
    public void queuw(WiselyMessage rm) {
            /*使用convertAndSendToUser方法,第一个参数为用户id,此时js中的订阅地址为
            "/user/" + 用户Id + "/message",其中"/user"是固定的*/
            template.convertAndSendToUser("zhangsan","/message",rm.getName());
        }

}

 SimpMessagingTemplate类的源码:

4.在src/main/resource包下建一个static包,引入jquery.min.js、sock.min.js、stomp.min.js,创建ws.html。

静态资源结构:

ws.html:

<html>
<head>
    <meta charset="UTF-8">
    <title>Hello queue</title>
    <script src="./sockjs.min.js"></script>
    <script src="./stomp.min.js"></script>
    <script src="./jquery.js"></script>
    <script type="text/javascript">
        var stompClient = null;
        function setConnected(connected){
            document.getElementById("connect").disabled = connected;
            document.getElementById("disconnect").disabled = !connected;
            $("#response").html();
        }
        function connect() {
            var socket = new SockJS("/queueServer");
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function(frame) {
                setConnected(true);
                console.log('Connected: ' + frame);
                stompClient.subscribe('/user/'+document.getElementById('user').value+'/message', function(response){
                    var response1 = document.getElementById('response');
                    var p = document.createElement('p');
                    p.style.wordWrap = 'break-word';
                    p.appendChild(document.createTextNode(response.body));
                    response1.appendChild(p);
                });
            });
        }

        function disconnect() {
            if (stompClient != null) {
                stompClient.disconnect();
            }
            setConnected(false);
            console.log("Disconnected");
        }

        function sendName() {
            var name = document.getElementById('name').value;
            console.info(1111111111);
            stompClient.send("/queue", {}, JSON.stringify({ 'name': name}));
        }
    </script>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! Websocket relies on Javascript being enabled. Please enable
    Javascript and reload this page!</h2></noscript>
<div>
    <div>
        <labal>用户</labal><input type="text" id="user" />
        <button id="connect" onclick="connect();">Connect</button>
        <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button>
    </div>
    <div id="conversationDiv">
        <labal>名字</labal><input type="text" id="name" />
        <button id="sendName" onclick="sendName();">Send</button>
        <p id="response"></p>
    </div>
</div>

</body>
</html>

5.WebMvcConfig,访问静态页面配置

package com.example.wwbsocket;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/ws").setViewName("/ws");
    }
}

6.测试

以不同的用户名建立连接。发送的消息都集中推送到了订阅zhangsan的客户端

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页