項目需求
- 使用 springboot websocket 定時任務 實現消息的
實現步驟
- 打開 eclipse ,新建一個 springboot 項目
- pom.xml 中加入相關依賴,如下
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- websocket 依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>
package com.example.demo;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
package com.example.demo;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
@ServerEndpoint(value = "/wsdemo")
@Component
public class MyWebSocket {
/**靜態變量,用來記錄當前在線連接數。應該把它設計成線程安全的。*/
private static int onlineCount = 0;
/** concurrent包的線程安全Set,用來存放每個客戶端對應的MyWebSocket對象。
在外部可以獲取此連接的所有websocket對象,並能對其觸發消息發送功能,我們的定時發送核心功能的實現在與此變量 */
private static CopyOnWriteArraySet<MyWebSocket> webSocketSet = new CopyOnWriteArraySet<MyWebSocket>();
/**與某個客戶端的連接會話,需要通過它來給客戶端發送數據*/
private Session session;
/**
* 連接建立成功調用的方法
*
* 類似dwr的onpage方法,參考之前文章中demo有
* */
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this); //加入set中
addOnlineCount(); //在線數加1
System.out.println("有新連接加入!當前在線人數爲" + getOnlineCount());
try {
sendMessage("連接已建立成功.");
} catch (Exception e) {
System.out.println("IO異常");
}
}
/**
* 連接關閉調用的方法
*
* 參考dwrsession摧毀方法
*/
@OnClose
public void onClose() {
webSocketSet.remove(this); //連接關閉後,將此websocket從set中刪除
subOnlineCount(); //在線數減1
System.out.println("有一連接關閉!當前在線人數爲" + getOnlineCount());
}
/**
* 收到客戶端消息後調用的方法
*
* @param message 客戶端發送過來的消息*/
@OnMessage
public void onMessage(String message, Session session) {
System.out.println("來自客戶端的消息:" + message);
}
// 錯誤提示
@OnError
public void onError(Session session, Throwable error) {
System.out.println("發生錯誤");
error.printStackTrace();
}
// 發送消息,在定時任務中會調用此方法
public void sendMessage(String message) throws IOException {
this.session.getBasicRemote().sendText(message);
}
// 發送消息,在定時任務中會調用此方法 發送user 可以自定義發送的數據
public void sendMessageUser(User user) throws IOException {
this.session.getBasicRemote().sendText(user.toString());
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineCount--;
}
public Session getSession() {
return session;
}
public void setSession(Session session) {
this.session = session;
}
public static CopyOnWriteArraySet<MyWebSocket> getWebSocketSet() {
return webSocketSet;
}
public static void setWebSocketSet(CopyOnWriteArraySet<MyWebSocket> webSocketSet) {
MyWebSocket.webSocketSet = webSocketSet;
}
}
package com.example.demo;
import java.io.IOException;
import java.util.Date;
import java.util.concurrent.CopyOnWriteArraySet;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
@Component
@EnableScheduling
public class TimeTask {
@Scheduled(cron = "0/10 * * * * ?") // 每分鐘執行一次
public void test() {
System.err.println("********* 定時任務執行 **************");
CopyOnWriteArraySet<MyWebSocket> webSocketSet = MyWebSocket.getWebSocketSet();
webSocketSet.forEach(c -> {
try {
// c.sendMessage(" 定時發送 " + new Date().toLocaleString());
c.sendMessageUser(new User());
} catch (IOException e) {
e.printStackTrace();
}
});
System.err.println("。。。。。。。。。 定時任務完成 。。。。。。。。。。。。");
}
}
package com.example.demo;
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public User() {
this.name="123";
this.age = 123;
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebsocketTestApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketTestApplication.class, args);
}
}
- 網頁代碼 static 下面的index.html 頁面
<!DOCTYPE HTML>
<html>
<head>
<title>My WebSocket</title>
</head>
<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>
<script type="text/javascript">
var websocket = null;
//判斷當前瀏覽器是否支持WebSocket ,主要此處要更換爲自己的地址
if('WebSocket' in window){
websocket = new WebSocket("ws://localhost:8080/wsdemo");
}
else{
alert('Not support websocket')
}
//連接發生錯誤的回調方法
websocket.onerror = function(){
console.log("error");
setMessageInnerHTML("error");
};
//連接成功建立的回調方法
websocket.onopen = function(event){
console.log("open");
setMessageInnerHTML("open");
}
//接收到消息的回調方法
websocket.onmessage = function(event){
console.log(event.data);
setMessageInnerHTML(event.data);
}
//連接關閉的回調方法
websocket.onclose = function(){
console.log("close");
setMessageInnerHTML("close");
}
//監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function(){
websocket.close();
}
//將消息顯示在網頁上
function setMessageInnerHTML(innerHTML){
document.getElementById('message').innerHTML += innerHTML + '<br/>';
}
//關閉連接
function closeWebSocket(){
websocket.close();
}
//發送消息
function send(){
var message = document.getElementById('text').value;
websocket.send(message);
}
</script>
</html>
參考案例