终于实现了 SpringBoot+WebSocket实时监控异常....
阅读本文大概需要 4.5 分钟。
来自:cnblogs.com/jae-tech/p/15409340.html
<html>
<head>
<meta charset="utf-8" />
<title>实时监控title>
head>
<style>
.item {
display: flex;
border-bottom: 1px solid #000000;
justify-content: space-between;
width: 30%;
line-height: 50px;
height: 50px;
}
.item span:nth-child(2){
margin-right: 10px;
margin-top: 15px;
width: 20px;
height: 20px;
border-radius: 50%;
background: #55ff00;
}
.nowI{
background: #ff0000 ;
}
style>
<body>
<div id="app">
<div v-for="item in list" class="item">
<span>{{item.id}}.{{item.name}}span>
<span :class='item.state==-1?"nowI":""'>span>
div>
div>
body>
<script src="./js/vue.min.js">script>
<script type="text/javascript">
var vm = new Vue({
el: "#app",
data: {
list: [{
id: 1,
name: '张三',
state: 1
},
{
id: 2,
name: '李四',
state: 1
},
{
id: 3,
name: '王五',
state: 1
},
{
id: 4,
name: '韩梅梅',
state: 1
},
{
id: 5,
name: '李磊',
state: 1
},
]
}
})
var webSocket = null;
if ('WebSocket' in window) {
//创建WebSocket对象
webSocket = new WebSocket("ws://localhost:18801/webSocket/" + getUUID());
//连接成功
webSocket.onopen = function() {
console.log("已连接");
webSocket.send("消息发送测试")
}
//接收到消息
webSocket.onmessage = function(msg) {
//处理消息
var serverMsg = msg.data;
var t_id = parseInt(serverMsg) //服务端发过来的消息,ID,string需转化为int类型才能比较
for (var i = 0; i < vm.list.length; i++) {
var item = vm.list[i];
if(item.id == t_id){
item.state = -1;
vm.list.splice(i,1,item)
break;
}
}
};
//关闭事件
webSocket.onclose = function() {
console.log("websocket已关闭");
};
//发生了错误事件
webSocket.onerror = function() {
console.log("websocket发生了错误");
}
} else {
alert("很遗憾,您的浏览器不支持WebSocket!")
}
function getUUID() { //获取唯一的UUID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
script>
html>
#端口
server:
port: 18801
#密码,因为接口不需要权限,所以加了个密码做校验
mySocket:
myPwd: jae_123
@Configuration
public class WebSocketConfig {
/**
* 注入一个ServerEndpointExporter,该Bean会自动注册使用@ServerEndpoint注解申明的websocket endpoint
*/
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
/**
* @author jae
* @ServerEndpoint("/webSocket/{uid}") 前端通过此URI与后端建立链接
*/
"/webSocket/{uid}") (
@Component
public class WebSocketServer {
private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。
private static final AtomicInteger onlineNum = new AtomicInteger(0);
//concurrent包的线程安全Set,用来存放每个客户端对应的WebSocketServer对象。
private static CopyOnWriteArraySet
sessionPools = new CopyOnWriteArraySet ();
/**
* 有客户端连接成功
*/
public void onOpen(Session session, @PathParam(value = "uid") String uid){
sessionPools.add(session);
onlineNum.incrementAndGet();
log.info(uid + "加入webSocket!当前人数为" + onlineNum);
}
/**
* 连接关闭调用的方法
*/
public void onClose(Session session) {
sessionPools.remove(session);
int cnt = onlineNum.decrementAndGet();
log.info("有连接关闭,当前连接数为:{}", cnt);
}
/**
* 发送消息
*/
public void sendMessage(Session session, String message) throws IOException {
if(session != null){
synchronized (session) {
session.getBasicRemote().sendText(message);
}
}
}
/**
* 群发消息
*/
public void broadCastInfo(String message) throws IOException {
for (Session session : sessionPools) {
if(session.isOpen()){
sendMessage(session, message);
}
}
}
/**
* 发生错误
*/
public void onError(Session session, Throwable throwable){
log.error("发生错误");
throwable.printStackTrace();
}
}
@RestController
@RequestMapping( )
public class WebSocketController {
public String myPwd;
private WebSocketServer webSocketServer;
/**
* 手机客户端请求接口
* @param id 发生异常的设备ID
* @param pwd 密码(实际开发记得加密)
* @throws IOException
*/
public void onReceive(String id,String pwd) throws IOException {
if(pwd.equals(myPwd)){ //密码校验一致(这里举例,实际开发还要有个密码加密的校验的),则进行群发
webSocketServer.broadCastInfo(id);
}
}
}
推荐阅读:
内容包含Java基础、JavaWeb、MySQL性能优化、JVM、锁、百万并发、消息队列、高性能缓存、反射、Spring全家桶原理、微服务、Zookeeper、数据结构、限流熔断降级......等技术栈!
⬇戳阅读原文领取! 朕已阅
评论