告警功能增加

This commit is contained in:
weiweiw 2024-11-08 18:46:05 +08:00
parent 05196751c7
commit 9f8c5303a9
7 changed files with 146 additions and 79 deletions

View File

@ -7,12 +7,12 @@ spring:
nacos:
discovery:
# 服务注册地址
server-addr: 192.168.0.56:8848
namespace: 9cde1ce1-98bc-4b9c-9213-f1fbf8a5b3cc
server-addr: 192.168.0.14:8848
namespace: f648524d-0a7b-449e-8f92-64e05236fd51
config:
# 配置中心地址
server-addr: 192.168.0.56:8848
namespace: 9cde1ce1-98bc-4b9c-9213-f1fbf8a5b3cc
server-addr: 192.168.0.14:8848
namespace: f648524d-0a7b-449e-8f92-64e05236fd51
# 配置文件格式
file-extension: yml
# 共享配置

View File

@ -96,6 +96,19 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.0.18</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
</dependencies>

View File

@ -30,4 +30,17 @@ public class SysWarning {
private Date warningTime;
private String warningStatus = "0";
public String toString() {
return "SysWarning{" +
"warningId='" + warningId + '\'' +
", warningEvent='" + warningEvent + '\'' +
", warningContent='" + warningContent + '\'' +
", warningIp='" + warningIp + '\'' +
", warningGrade='" + warningGrade + '\'' +
", operaUserName='" + operaUserName + '\'' +
", warningTime=" + warningTime +
", warningStatus='" + warningStatus + '\'' +
'}';
}
}

View File

@ -1,52 +0,0 @@
package com.bonus.system.warning;
import com.bonus.system.service.ISysLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;
import javax.annotation.Resource;
import java.io.IOException;
@Component
@Slf4j
public class WarningListen {
@Autowired
private SimpMessagingTemplate messagingTemplate;
@Resource(name = "ISysLogService")
private ISysLogService service;
public static void closeSession(WebSocketSession session) throws IOException {
session.close();
}
@EventListener
public void onLogSaved(WaringLogEvent event) {
try {
SysWarning warning = event.getSysWarning();
sendAlert(warning);
} catch (Exception e) {
log.error("处理日志告警失败", e);
}
}
// 发送告警消息
public void sendAlert(SysWarning alert) {
messagingTemplate.convertAndSend("/topic/alerts", alert);
log.info("*************************告警消息已发送:{}", alert);
}
// 处理用户确认消息
@MessageMapping("/alert-handled")
public void handleAlert(String alertId) {
// 在这里处理告警确认逻辑
System.out.println("Alert " + alertId + " has been handled");
}
}

View File

@ -1,31 +1,17 @@
package com.bonus.system.warning;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.config.annotation.*;
/**
* @author wangvivi
*/
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer, WebSocketConfigurer {
@Autowired
private WebSocketHandler webSocketHandler;
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws-alert").withSockJS();
}
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(webSocketHandler, "/ws-alert")
.setAllowedOrigins("*"); // 允许跨域
registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*");
}
}
}

View File

@ -1,11 +1,20 @@
package com.bonus.system.warning;
import com.alibaba.fastjson.JSON;
import com.bonus.system.service.ISysLogService;
import org.springframework.context.event.EventListener;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.messaging.SessionConnectedEvent;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArrayList;
@Component
@ -13,6 +22,56 @@ public class WebSocketHandler extends TextWebSocketHandler {
private static final Logger logger = LoggerFactory.getLogger(WebSocketHandler.class);
private static final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
@Resource(name = "ISysLogService")
private ISysLogService service;
public static void closeSession(WebSocketSession session) throws IOException {
session.close();
}
/**
*
* @event 监听异常日志推送到前端
*/
@EventListener
public void onLogSaved(WaringLogEvent event) {
try {
SysWarning warning = event.getSysWarning();
String jsonStr = JSON.toJSONString(warning);
sendMessageToAll(jsonStr);
} catch (Exception e) {
System.out.print("处理日志告警失败");
}
}
/**
*
* @event 监听socket连接
*/
@EventListener
public void handleWebSocketConnectListener(SessionConnectedEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
System.out.println("WebSocket 连接建立Session ID: " + headerAccessor.getSessionId());
}
/**
*
* @event 监听socket断开连接
*/
@EventListener
public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) {
StompHeaderAccessor headerAccessor = StompHeaderAccessor.wrap(event.getMessage());
System.out.println("WebSocket 连接断开Session ID: " + headerAccessor.getSessionId());
}
// 处理用户确认消息
@MessageMapping("/alert-handled")
public void handleAlert(String alertId) {
// 在这里处理告警确认逻辑
System.out.println("Alert " + alertId + " has been handled");
}
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
sessions.add(session);
@ -37,4 +96,10 @@ public class WebSocketHandler extends TextWebSocketHandler {
sessions.remove(session);
logger.info("WebSocket 连接关闭: " + session.getId());
}
public void sendMessageToAll(String message) throws Exception {
for (WebSocketSession session : sessions) {
session.sendMessage(new TextMessage(message));
}
}
}

View File

@ -68,6 +68,15 @@ create table sys_user (
primary key (user_id)
) engine=innodb auto_increment=100 comment = '用户信息表';
ALTER TABLE `bns-cloud`.sys_user ADD is_permanent char(1) DEFAULT '1' NULL COMMENT '长期和临时用户标识0临时用户1长期用户';
ALTER TABLE `bns-cloud`.sys_user ADD is_built_in char(1) DEFAULT '0' NULL COMMENT '是否内置用户0非内置用户1内置用户';
ALTER TABLE `bns-cloud`.sys_dept MODIFY COLUMN phone varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '联系电话';
ALTER TABLE `bns-cloud`.sys_dept MODIFY COLUMN email varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL COMMENT '邮箱';
ALTER TABLE `bns-cloud`.sys_user MODIFY COLUMN email varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '用户邮箱';
ALTER TABLE `bns-cloud`.sys_user MODIFY COLUMN phonenumber varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '' NULL COMMENT '手机号码';
-- ----------------------------
-- 初始化-用户信息表数据
-- ----------------------------
@ -127,7 +136,9 @@ create table sys_role (
primary key (role_id)
) engine=innodb auto_increment=100 comment = '角色信息表';
-- ----------------------------
ALTER TABLE `bns-cloud`.sys_role ADD is_built_in char(1) DEFAULT '0' NULL COMMENT '是否内置0非内置角色1内置角色';
----------------------
-- 初始化-角色信息表数据
-- ----------------------------
insert into sys_role values('1', '超级管理员', 'admin', 1, 1, 1, 1, '0', '0', 'admin', sysdate(), '', null, '超级管理员','1');
@ -761,3 +772,34 @@ create table sys_logs_set (
insert into sys_logs_set values ('2048');
-- ------------------------------
-- 22 waring table
-- ------------------------------
drop table if exists sys_warning;
create table sys_warning (
warning_id bigint(20) not null auto_increment comment '编号',
warning_event varchar(50) default '' comment '告警事件',
warning_content varchar(50) default '' comment '告警内容',
warning_ip varchar(50) default '' comment '告警IP',
warning_grade varchar(50) default '' comment '告警等级',
opera_user_name varchar(50) default '' comment '操作人名称',
warning_time datetime default sysdate comment '告警时间',
warning_status char(1) default '0' comment '告警状态0未处理1已处理',
primary key (warning_id)
) engine = innodb comment = '报警日志表';
drop table if exists sys_ip_whitelist;
CREATE TABLE `sys_ip_whitelist` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`ip_address` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT '单个IP地址',
`ip_range_start` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'IP网段起始地址',
`ip_range_end` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL COMMENT 'IP网段结束地址',
`access_start_time` timestamp NULL DEFAULT NULL COMMENT '允许访问的开始时间',
`access_end_time` timestamp NULL DEFAULT NULL COMMENT '允许访问的结束时间',
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间',
`updated_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间',
`status` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT '0' COMMENT '帐号状态0正常 1停用',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = innodb CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;