前期準備
申請一個ssl證書免費的就可以
阿里雲:https://common-buy.aliyun.com/?commodityCode=cas#/buy
然後下載證書
我們需要這個 .key 文件,把該文件放在spring boot項目resources目錄下,配置文件中添加
application.yml
server:
port: 443
servlet:
context-path: /
ssl:
key-store: classpath:21427867.pfx
key-store-password: 21427867
key-store-type: PKCS12
登陸微信公衆平臺 小程序後臺 設置-》開發設置-》服務器域名
本機調試,我們還需要做一個內網映射,花生殼,路由器端口映射,dmz主機,都可以。
dmz主機可以利用阿里雲的域名解析接口,自己寫一個服務,實時更新A記錄的值爲我們本機的公網ip,這就實現了動態解析的功能。
開始
可以參考spring官網案例創建websocket服務端
網址:https://spring.io/guides/gs/messaging-stomp-websocket/
我的是這麼寫的
WebSocketConfig.java
package com.huayu.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
/**
* 配置了一個簡單的消息代理,如果不重載,默認情況下回自動配置一個簡單的內存消息代理,用來處理以"/topic"爲前綴的消息。這裏重載configureMessageBroker()方法,
* 消息代理將會處理前綴爲"/topic"和"/queue"的消息。
*/
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// 這句話表示在topic和user這兩個域上可以向客戶端發消息。
config.enableSimpleBroker("/topic", "/user");
// 這句話表示客戶單向服務器端發送時的主題上面需要加"/app"作爲前綴。
config.setApplicationDestinationPrefixes("/app");
// 這句話表示給指定用戶發送一對一的主題前綴是"/user"。
config.setUserDestinationPrefix("/user");
}
/**
* 將"/gs-guide-websocket"路徑註冊爲STOMP端點,這個路徑與發送和接收消息的目的路徑有所不同,這是一個端點,客戶端在訂閱或發佈消息到目的地址前,要連接該端點,
* 即用戶發送請求url="/gs-guide-websocket"與STOMP server進行連接。之後再轉發到訂閱url;
* PS:端點的作用——客戶端在訂閱或發佈消息到目的地址前,要連接該端點。
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
/*
* 在網頁上可以通過"/gs-guide-websocket"來和服務器的WebSocket連接
*這個和客戶端創建連接時的url有關,其中setAllowedOrigins()方法表示允許連接的域名,withSockJS()方法表示支持以SockJS方式連接服務器。
*/
registry.addEndpoint("/gs-guide-websocket").setAllowedOrigins("*");
}
}
WebSocketTestController.java
package com.huayu.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessageSendingOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* webSocket測試
*
* @author lihy
* @version 2018/6/15
*/
@Controller
public class WebSocketTestController {
@Autowired
SimpMessageSendingOperations simpMessageSendingOperations;
/**
* 定時推送消息
*
* @author lihy
*/
@Scheduled(fixedRate = 1000)
public void callback() {
// 發現消息
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
simpMessageSendingOperations.convertAndSend("/topic/greetings", "廣播消息" + df.format(new Date()));
}
/**
* 發送給單一客戶端
* 客戶端接收一對一消息的主題應該是“/user/” + 用戶Id + “/message” ,這裏的用戶id可以是一個普通的字符串,只要每個用戶端都使用自己的id並且服務端知道每個用戶的id就行。
*
* @return java.lang.String
* @author lihy
*/
@RequestMapping(path = "/sendToUser", method = RequestMethod.GET)
@ResponseBody
public String sendToUser() {
String openid = "oO1Yu5Tlih1Lxqi7yh1qc7fZJE9M";
simpMessageSendingOperations.convertAndSendToUser(openid, "/message", "你好" + openid);
return "success";
}
/**
* 接收客戶端發來的消息
*
* @author lihy
*/
@MessageMapping("/helloServer")
public void receiver(String msg) {
System.out.println("msg = [" + msg + "]");
}
}
小程序
引入stomp模塊, 官網下載就可以了,地址:https://raw.githubusercontent.com/jmesnil/stomp-websocket/master/lib/stomp.js
js這樣寫
initSocket: function () {
var socketOpen = false
function sendSocketMessage(msg) {
console.log('send msg:')
console.log(msg);
if (socketOpen) {
wx.sendSocketMessage({
data: msg
})
} else {
socketMsgQueue.push(msg)
}
}
var ws = {
send: sendSocketMessage
}
wx.connectSocket({
url: 'wss://***.**.com/gs-guide-websocket'
})
wx.onSocketOpen(function (res) {
socketOpen = true
ws.onopen()
})
wx.onSocketMessage(function (res) {
ws.onmessage(res)
})
var Stomp = require('../../utils/stomp.min.js').Stomp;
Stomp.setInterval = function () { }
Stomp.clearInterval = function () { }
var stompClient = Stomp.over(ws);
stompClient.connect({}, function (sessionId) {
stompClient.subscribe('/topic/greetings', function (body, headers) {
console.log('From MQ:', body);
});
let openid = 'oO1Yu5Tlih1Lxqi7yh1qc7fZJE9M';
stompClient.subscribe('/user/' + openid + '/message', function (body, headers) {
wx.vibrateLong()
console.log('From MQ to user:', body);
});
stompClient.send("/app/helloServer", {}, JSON.stringify({ 'msg': '我是客戶端' }));
})
}
小程序輸出
springboot輸出
訪問:https://你的域名/sendToUser
小程序客戶端也接收到了