项目需求
- 使用 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>
参考案例