前面几个小节我们已经学习了stomp协议,了解了stomp客户端的用法,并且搭建了一个小的后台demo,前端页面通过html页面与后端服务建立WebSocket连接。发送消息给后端服务。后端服务将消息内容原样送回。通过这个demo我们学习了前端stomp客户端的用法,同时也学到了如何通过spring-boot来搭建一个websocket平台。
本节我们将继续深入,搭建一套可用于生产的websocket平台。
基本介绍
websocket连接推送服务包含两个服务,websocket-connector和websocket-gateway。
架构如上图
websocket-connector
- 作为和客户端建立websocket连接的服务,负责消息的接收和推送
websocket-gateway
- 作为后台服务,提供http接口给其他微服务,其他微服务可以通过http接口发送消息给指定的用户
使用说明
通过下面的步骤来进行调试
- 分别启动项目websocket-connector和websocket-gateway
- 访问下面接口,获取某个用户的token
下面示例是获取用户1001的token
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{
\"userId\":\"1001\"}" "http://localhost:8081/api/ws/token/get"
-
打开websocket-connector调试页面http://localhost:8080/index.html
将上一个接口获取到的token作为参数,与服务器建立连接
-
通过页面的send按钮,发送一条消息给服务器,同时服务器会将此消息回复给前端页面。参考上图
-
通过websocket-gateway的接口,发送用户单播消息
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{
\"appCode\":\"test2\",\"messageData\":{
\"body\":\"single message\",\"headers\":{}},\"topic\":\"/user/topic/single/hello\",\"userIds\":[1001]}" "http://localhost:8081/api/ws/message/single/send"
前端页面可以收到该消息的推送
6.通过websocket-gateway的接口,发送广播消息
curl -X POST -H "Accept:*/*" -H "Content-Type:application/json" -d "{
\"appCode\":\"test1\",\"messageData\":{
\"body\":\"hello board message1\",\"headers\":{}},\"topic\":\"/topic/boardCast/hello\"}" "http://localhost:8081/api/ws/message/boardCast/send"
主要代码分析
前端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>STOMP</title>
</head>
<body onload="disconnect()">
<h1 id="tip">消息发布订阅测试页</h1>
请输入token:<input type="text" id="token" placeholder=""> <br>
<button onclick="connect()" id="connect">connect</button>
<button onclick="disconnect()" id="disconnect">disconnect</button>
<p>输入消息: <span id="msg"></span></p>
<input type="text" id="content" placeholder=""> <br>
<button onclick="send()">send</button>
<ul id="ul">
回答消息<p id="answer"></p>
单播消息<p id="single"></p>
广播消息<p id="board"></p>