springboot支持webSocket和stomp实现消息订阅通知示例

springboot支持webSocket和stomp实现消息订阅通知示例

先导入支持websocket的jar包,这里用Gradle构建的项目:
dependencies {
    compile('org.springframework.boot:spring-boot-starter-websocket')
}
webSocket的配置文件,实现了WebSocketMessageBrokerConfigurer接口:
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        //允许使用socketJs方式访问,访问点为webSocket,允许跨域
        //在网页上我们就可以通过这个链接
        //ws://127.0.0.1:2222/webSocket来和服务器的WebSocket连接
        registry.addEndpoint("/webSocket").setAllowedOrigins("*");
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry registry) {
        //基于内存的STOMP消息代理来代替mq的消息代理
        //订阅Broker名称,/user代表点对点即发指定用户,/topic代表发布广播即群发
        registry.enableSimpleBroker("/user", "/topic");
        //点对点使用的订阅前缀,不设置的话,默认也是/user/
        registry.setUserDestinationPrefix("/user/");
    }
}

Javascript客户端代码:
var stompClient = null; 
//加载完浏览器后  调用connect(),打开双通道
$(function(){   
    //打开双通道
    connect()
})
//强制关闭浏览器  调用websocket.close(),进行正常关闭
    window.onunload = function() {
        disconnect()
    }
    function connect(){
        var groupId = 1
        var socket = new WebSocket("ws://127.0.0.1:2222/webSocket"); //连接SockJS的endpoint名称为"webSocket"
        stompClient = Stomp.over(socket);//使用STMOP子协议的WebSocket客户端
        console.log(stompClient)
        stompClient.connect({},function(frame){//连接WebSocket服务端     
            console.log('Connected:' + frame);
            //通过stompClient.subscribe订阅/topic/getResponse 目标(destination)发送的消息
            stompClient.subscribe('/user/'+groupId+'/refresh',function(response){
                console.log(response.body);
            });
        });
    }
 
    //关闭双通道
    function disconnect(){
        if(stompClient != null) {
            stompClient.disconnect();
        }
        console.log("Disconnected");
    }
    function showResponse(message){
        var response = $("#response");
        response.append("<p>"+message.userName+"</p>");
    }

如果链接成功,浏览器会打印如下信息:

点对点通信:

如果下面的接口被调用,服务器就会主动往所有连接服务器的客户端订阅了“/user/+“groupId”+/refresh”的路径推送消息

/**
     * websocket刷新流程
     * @author metadata
     */
    @GetMapping("refresh/{groupId}")
    public void refresh(@PathVariable Long groupId) {
        simpMessagingTemplate.convertAndSendToUser(groupId.toString(), "/refresh", "refresh");
    }

如果该接口被调用,相应的客户端会接收到如下消息:

原文地址: https://www.cnblogs.com/zys-blog/p/12091759.html

Comments are closed.