應用場景介紹:
在頁面的數據需要實時刷新的時候,或者在頁面需要接收後臺的消息時候,如果採用前端輪詢會造成資源佔用較大,並且數據刷新也是不及時的,比如當我後臺在監聽MQ的消息時候,當從MQ監聽到消息後我需要將MQ消息推送到前端實時展示,這時候就需要用到webSocket了。
1.首先搭建一個SpringBoot的項目,這裏我就不重複了,然後引入jar包
<!-- WebSocket -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
2、編寫websocketConfig配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Author dingchengxiang
* @Description //TODO WebSocket配置類
* @Date 15:53 2019/11/11
* @Param
* @return
**/
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3.websocket的實現類
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
@Component
@ServerEndpoint("/push/websocket")
@Slf4j
public class WebSocketServer {
//靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。
private static int onlineCount = 0;
//concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
private static CopyOnWriteArraySet<WebSocketServer> webSocketSet = new CopyOnWriteArraySet<WebSocketServer>();
//與某個客戶端的連接會話,需要通過它來給客戶端發送數據
private Session session;
//接收sid
private String sid="";
/**
* 連接建立成功調用的方法*/
@OnOpen
public void onOpen(Session session,@PathParam("sid") String sid) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
log.info("有新窗口開始監聽:"+sid+",當前在線人數爲" + getOnlineCount());
this.sid=sid;
/*try {
sendMessage(JSON.toJSONString(RestResponse.success()));
} catch (IOException e) {
log.error("websocket IO異常");
}*/
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //從set中刪除
subOnlineCount(); //在線數減1
log.info("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
//log.info("收到來自窗口"+sid+"的信息:"+message);
if("heart".equals(message)){
try {
sendMessage("heartOk");
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發生錯誤");
error.printStackTrace();
}
/**
* 實現服務器主動推送
*/
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
/**
* 羣發自定義消息
* */
public static void sendInfo(String message) throws IOException {
for (WebSocketServer item : webSocketSet) {
try {
//這裏可以設定只推送給這個sid的,爲null則全部推送
// if(sid==null) {
item.sendMessage(message);
log.info("推送消息到窗口"+item.sid+",推送內容:"+message);
// }else if(item.sid.equals(sid)){
// item.sendMessage(message);
// }
} catch (IOException e) {
continue;
}
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServer.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServer.onlineCount--;
}
}
4、新增一個控制層接口作爲測試接口能夠調用的
/**
* @Author dingchengxiang
* @Description //TODO 測試websocket發送消息
* @Date 14:41 2019/11/12
* @Param []
* @return java.lang.String
**/
@PostMapping("/sendAllWebSocket")
public String test() {
String text="你們好!這是websocket羣體發送!";
try {
webSocketServer.sendInfo(text);
}catch (IOException e){
e.printStackTrace();
}
return text;
}
此處需要注意一下,後臺可能與攔截需要將接口放開,本人是在shiroConfig中進行設置
5、編寫前端vue的代碼
先在這兩處添加,
mounted () {
// WebSocket
if ('WebSocket' in window) {
this.websocket = new WebSocket('ws://localhost:8080/自己的項目地址/push/websocket')
// alert('連接瀏覽器')
this.initWebSocket()
} else {
alert('當前瀏覽器 不支持')
}
},
beforeDestroy () {
this.onbeforeunload()
},
然後在方法中編寫具體實現
methods: {
initWebSocket () {
// 連接錯誤
this.websocket.onerror = this.setErrorMessage
// 連接成功
this.websocket.onopen = this.setOnopenMessage
// 收到消息的回調
this.websocket.onmessage = this.setOnmessageMessage
// 連接關閉的回調
this.websocket.onclose = this.setOncloseMessage
// 監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = this.onbeforeunload
},
setErrorMessage () {
console.log('WebSocket連接發生錯誤 狀態碼:' + this.websocket.readyState)
},
setOnopenMessage () {
console.log('WebSocket連接成功 狀態碼:' + this.websocket.readyState)
},
setOnmessageMessage (event) {
// 根據服務器推送的消息做自己的業務處理
console.log('服務端返回:' + event.data)
},
setOncloseMessage () {
console.log('WebSocket連接關閉 狀態碼:' + this.websocket.readyState)
},
onbeforeunload () {
this.closeWebSocket()
},
closeWebSocket () {
this.websocket.close()
}
}
這個時候啓動我們就可以看到效果了,頁面控制檯打印的值
後臺控制檯打印的值
到這一步基本的就已經實現了,但是我們現在要加入中間件MQ監聽到消息後進行消息返回,那麼還需要下面幾步,
6、MQ我在這個demo中沒有集成,我就用一個定時任務來模擬MQ監聽到消息以後的處理步驟。
新建一個Task類
/**
* @Author dingchengxiang
* @Description //TODO 消息定時器,通知websocket
* @Date 14:56 2019/11/12
* @Param
* @return
**/
@Component
public class Task {
@Autowired
private WebSocketServer webSocketServer;
/**
* @throws Exception
*/
@Scheduled(cron="0/5 * * * * ? ")
public void JqcaseSearch() {
try {
System.out.println("這是心跳");
webSocketServer.sendInfo("主動推送消息");
} catch (Exception e) {
e.printStackTrace();
}
}
}
這麼設置,每隔五秒,就會模擬MQ監聽到一條消息,然後調用WebSocket服務的發送消息,此時我們需要在啓動類上面加一個定時器註解
@SpringBootApplication
@EnableScheduling
public class Application {
public static void main(String[] args) {
SpringApplication.run(RenrenApplication.class, args);
}
}
加上@EnableScheduling註解後定時器纔會有效果
這時候我們再編寫個簡單的html頁面來幫助我們觀察
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<title>websocket測試頁面</title>
</head>
<body>
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-md-6">
<div class="input-group">
<span class="input-group-addon">ws地址</span>
<input type="text" id="address" class="form-control" placeholder="ws地址"
aria-describedby="basic-addon1" value="ws://localhost:8080/自己的項目/push/websocket">
<div class="input-group-btn">
<button class="btn btn-default" type="submit" id="connect">連接</button>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 10px;display: none;" id="msg-panel">
<div class="col-md-6">
<div class="input-group">
<span class="input-group-addon">消息</span>
<input type="text" id="msg" class="form-control" placeholder="消息內容" aria-describedby="basic-addon1">
<div class="input-group-btn">
<button class="btn btn-default" type="submit" id="send">發送</button>
</div>
</div>
</div>
</div>
<div class="row" style="margin-top: 10px; padding: 10px;">
<div class="panel panel-default">
<div class="panel-body" id="log" style="height: 450px;overflow-y: auto;">
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js"
integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function () {
var _socket;
$("#connect").click(function () {
_socket = new _websocket($("#address").val());
_socket.init();
});
$("#send").click(function () {
var _msg = $("#msg").val();
output("發送消息:" + _msg);
_socket.client.send(_msg);
});
});
function output(e) {
var _text = $("#log").html();
$("#log").html(_text + "<br>" + e);
}
function _websocket(address) {
this.address = address;
this.client;
this.init = function () {
if (!window.WebSocket) {
this.websocket = null;
return;
}
var _this = this;
var _client = new window.WebSocket(_this.address);
_client.onopen = function () {
output("websocket打開");
$("#msg-panel").show();
};
_client.onclose = function () {
_this.client = null;
output("websocket關閉");
$("#msg-panel").hide();
};
_client.onmessage = function (evt) {
output(evt.data);
};
_this.client = _client;
};
return this;
}
</script>
</body>
</html>
這時候啓動SpringBoot,再運行html,
此時連接後我們會發現,後臺會一直向頁面推送消息
同時在VUE的控制檯也會發現
有消息產生,到此demo就結束了,我們可以利用返回的消息做數據刷新,做消息推送等。
2019年11月13日補充:
需要對列表進行推送刷新的話,有兩種將數據推送的方式
1、修改發送的消息爲Object類型
/**
* 實現服務器主動推送
*/
public void sendMessage(Object message) throws Exception {
this.session.getBasicRemote().sendObject(message);
}
但是修改之後發現會報錯
提示我沒有編碼類。
之後查閱一下,發現需要編碼類,比較麻煩,就沒有才用了
2、採用json字符串的方式發送到前端,FastJsonUtils是我自己編寫的json工具類
public void JqcaseSearch() {
Map<String, Object> params = new HashMap<>();
params.put("t","1573630630476");
params.put("page","1");
params.put("limit","10");
PageUtils page = sysRoleService.queryPage(params);
JSONObject jsonObject = FastJsonUtils.toJsonObject(R.ok().put("page", page));
try {
webSocketServer.sendData(jsonObject);
} catch (Exception e) {
e.printStackTrace();
}
}
再編寫調用類
/**
* 自定義刷新數據
* */
public static void sendData(JSONObject object) throws Exception {
for (WebSocketServer item : webSocketSet) {
try {
item.sendMessage(object.toJSONString());
log.info("推送消息到窗口,推送內容:"+object);
} catch (IOException e) {
continue;
}
}
再調用主動推送的方法
/**
* 實現服務器主動推送
*/
public void sendMessage(String message) throws Exception {
/* this.session.getBasicRemote().sendObject(message);*/
this.session.getBasicRemote().sendText(message);
}
最後到頁面將字符串轉化爲jsondata
最後再根據自己的實際頁面將jsondata裏的數據放到到頁面上去