websocket数据库数据变化实时推送前端
最近项⽬上有需要,先写了⼀个demo⽤于记录和研究websocket,代码有些是借鉴了其他前辈的代码,有些是⾃⼰的,还包括⼀些踩坑主要⽤于需要后端想前端进⾏数据库变化时推送刷新页⾯通知。
WebSocketServlet
这个主要⽤于配置⽅法以及在⽅法内轮询线程查询数据库
import com.service.IdentifyRecordService;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import urrent.CopyOnWriteArraySet;
//在相对路径中发布端点websocket
@ServerEndpoint("/websocket")
@Component
public class WebSocketServlet {
MyThread thread1=new MyThread();
Thread thread=new Thread(thread1);
@Resource
private IdentifyRecordService identifyRecordService;
//⽤来存放每个客户端对应的MyWebSocket对象。
private static CopyOnWriteArraySet<WebSocketServlet> webSocketSet =new CopyOnWriteArraySet<WebSocketServlet>();
private javax.websocket.Session session=null;
/**
* @ClassName: onOpen
* @Description: 开启连接的操作
*/
@OnOpen
public void onOpen(Session session)throws IOException{
this.session=session;
webSocketSet.add(this);
System.out.println(webSocketSet);
//开启⼀个线程对数据库中的数据进⾏轮询
thread.start();
}
/**
* @ClassName: onClose
* @Description: 连接关闭的操作
*/
@OnClose
public void onClose(){
thread1.stopMe();
}
/**
* @ClassName: onMessage
* @Description: 给服务器发送消息告知数据库发⽣变化
*/
@OnMessage
public void onMessage(int count){
System.out.println("发⽣变化"+count);
try{
sendMessage();
sendMessage();
}catch(IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @ClassName: OnError
* @Description: 出错的操作
*/
@OnError
public void onError(Throwable error){
System.out.println(error);
error.printStackTrace();
}
/**
* 这个⽅法与上⾯⼏个⽅法不⼀样。没有⽤注解,是根据⾃⼰需要添加的⽅法。
* @throws IOException
* 发送⾃定义信号,“1”表⽰告诉前台,数据库发⽣改变了,需要刷新
*/前端websocket怎么用
public void sendMessage()throws IOException {
//发消息
for(WebSocketServlet item: webSocketSet){
BasicRemote().sendText("1");
}
}
}
WebSocketConfig
配置类,照搬即可
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
System.out.println("我被注⼊了");
return new ServerEndpointExporter();
}
}
MyThread
线程⽅法,⽤于调⽤指定的服务,但是服务需要各位⾃⼰修改了,注意如果不添加⼀个⼯具类是⽆法想线程内注⼊bean的
import com.service.Service;
public class MyThread implements Runnable {
private int sum;
private int new_sum;
private boolean stopMe =true;
public void stopMe(){
stopMe =false;
}
private Service Bean(Service.class);
@Override
public void run(){
Long countall= untAll();
String s = String();
sum = Integer.parseInt(s);
WebSocketServlet wbs=new WebSocketServlet();
while(stopMe){
Long aLong = untAll();
String s2 = String();
new_sum=Integer.parseInt(s2);
if(sum!=new_sum){
System.out.println("change");
sum=new_sum;
}
try{
Thread.sleep(1000);
}catch(InterruptedException e){
/
/ TODO Auto-generated catch block
e.printStackTrace();
}
}
}
BeanContext
⼿动注⼊线程的⼯具类,直接使⽤即可
import org.springframework.beans.BeansException;
import t.ApplicationContext;
import t.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class BeanContext implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext)throws BeansException { BeanContext.applicationContext = applicationContext;
}
public static<T> T getBean(Class<T> clz)throws BeansException {
return(T) Bean(clz);
}
}
静态页⾯ ⽤于测试websocket,有需要⾃取
<html>
<head>
<meta charset="UTF-8">
<title>websocket测试</title>
<script src="libs.baidu/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
h3,h4{
text-align:center;
}
</style>
</head>
<body>
<h3>WebSocket测试,客户端接收到的消息如下:</h3>
<textarea id ="messageId" readonly="readonly" cols="150" rows="30">
</textarea>
<script type="text/javascript">
var websocket =null;
//判断当前浏览器是否⽀持WebSocket
if('WebSocket'in window){
//建⽴连接,这⾥的/websocket ,是Servlet中注解中的那个值
websocket =new WebSocket("ws://localhost:8080/websocket");
}
else{
alert('当前浏览器 Not support websocket');
}
//连接发⽣错误的回调⽅法
console.log("WebSocket连接发⽣错误");
};
//连接成功建⽴的回调⽅法
console.log("WebSocket连接成功");
}
/
/接收到消息的回调⽅法
console.log(event.data);
if(event.data=="1"){
console.log("数据更新啦");
}
}
//连接关闭的回调⽅法
console.log("WebSocket连接关闭");
}
/
/监听窗⼝关闭事件,当窗⼝关闭时,主动去关闭WebSocket连接,防⽌连接还没断开就关闭窗⼝,server端会抛异常。 beforeunload=function(){
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket(){
websocket.close();
}
</script>
</body>
</html>
后续有⼼跳的需求等在添加,欢迎评论和交流
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论