From e7f4c234bddbeb63afc2efa6bc8fa6fec849c50d Mon Sep 17 00:00:00 2001 From: weiweiw <14335254+weiweiw22@user.noreply.gitee.com> Date: Tue, 12 Nov 2024 10:52:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=97=A5=E5=BF=97=E5=AE=B9=E9=87=8F=E8=BE=BE?= =?UTF-8?q?=E5=88=B0=E4=B8=8A=E9=99=90=E7=9A=8490%=E8=BF=9B=E8=A1=8C?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../bonus/system/api/RemoteConfigService.java | 4 +- .../factory/RemoteConfigFallbackFactory.java | 7 +- .../auth/controller/ConfigController.java | 1 + .../auth/controller/TokenController.java | 24 ++ .../service/PasswordValidatorService.java | 33 +- .../auth/service/SysPasswordService.java | 5 +- .../java/com/bonus/config/SystemConfig.java | 2 +- .../interceptor/ParamSecureHandler.java | 2 +- .../common/security/service/TokenService.java | 24 +- .../com/bonus/gateway/filter/IpFilter.java | 326 +++++++++--------- .../bonus/system/BonusSystemApplication.java | 2 + .../system/controller/SysLogController.java | 11 +- .../bonus/system/service/ISysLogService.java | 2 +- .../service/impl/SysLogServiceImpl.java | 33 +- .../service/impl/SysOperLogServiceImpl.java | 2 +- .../bonus/system/warning/ScheduledTasks.java | 31 ++ .../bonus/system/warning/WebSocketConfig.java | 2 +- .../src/main/resources/bootstrap.yml | 5 + sql/bns_20240604.sql | 12 +- 19 files changed, 300 insertions(+), 228 deletions(-) create mode 100644 bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/ScheduledTasks.java diff --git a/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/RemoteConfigService.java b/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/RemoteConfigService.java index 976554b..7505466 100644 --- a/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/RemoteConfigService.java +++ b/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/RemoteConfigService.java @@ -36,12 +36,12 @@ public interface RemoteConfigService { /** * 根据参数键名查询参数值 + * * @param configKey 参数键名 - * @param source 请求来源,使用SecurityConstants.INNER * @return 获取参数信息 */ @GetMapping(value = "/config/configKey/{configKey}") - public AjaxResult getConfigKey(@PathVariable("configKey") String configKey, @RequestHeader(SecurityConstants.FROM_SOURCE) String source); + public AjaxResult getConfigKey(@PathVariable("configKey") String configKey); /** * 新增参数配置 diff --git a/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/factory/RemoteConfigFallbackFactory.java b/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/factory/RemoteConfigFallbackFactory.java index 69877d5..de860d9 100644 --- a/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/factory/RemoteConfigFallbackFactory.java +++ b/bonus-api/bonus-api-system/src/main/java/com/bonus/system/api/factory/RemoteConfigFallbackFactory.java @@ -10,11 +10,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.cloud.openfeign.FallbackFactory; import org.springframework.stereotype.Component; -import org.springframework.validation.annotation.Validated; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestHeader; import java.util.ArrayList; import java.util.List; @@ -45,7 +40,7 @@ public class RemoteConfigFallbackFactory implements FallbackFactory isAdmin(@RequestBody LoginBody form) { if (!config.isAdmin()) { @@ -109,6 +120,19 @@ public class TokenController { if (form.getLoginType()== LoginType.EMAIL_OTP || form.getLoginType()== LoginType.PHONE_OTP ){ form.setPassword(form.getVerificationCode()); } + + /**对系统并发数进行判断*/ + long concurrency = 100; + AjaxResult result = configService.getConfigKey("sys.backend.concurrency"); + if (result.isSuccess()) + { + concurrency = Long.parseLong(result.get("msg").toString()); + } + Collection keys = redisService.keys(CacheConstants.LOGIN_TOKEN_KEY + "*"); + if (keys.size() >= concurrency){ + return R.fail("当前系统用户并发数超过系统配置,请稍后再试"); + } + LoginUser login = strategy.login(form.getUsername(), form.getPassword()); logService.saveLogin(form.getUsername(), "登录", "登录成功", null, "成功"); return R.ok(tokenService.createToken(login)); diff --git a/bonus-auth/src/main/java/com/bonus/auth/service/PasswordValidatorService.java b/bonus-auth/src/main/java/com/bonus/auth/service/PasswordValidatorService.java index 69bd486..2dcf1b1 100644 --- a/bonus-auth/src/main/java/com/bonus/auth/service/PasswordValidatorService.java +++ b/bonus-auth/src/main/java/com/bonus/auth/service/PasswordValidatorService.java @@ -298,12 +298,24 @@ public class PasswordValidatorService { // 如果 ipAddress 为空,检查是否在 ip 范围内 if (ObjectUtils.isEmpty(ipAddress)) { if (isIpInRange(ip, ipRangeStart, ipRangeEnd)) { - handleAccessTimeCheck(accessStartTime, accessEndTime); + boolean result = handleAccessTimeCheck(user, accessStartTime, accessEndTime); + if (!result) { + throw new ServiceException("ip地址异常"); + }else{ + return; + } } } else if (ipAddress.equals(ip)) { - handleAccessTimeCheck(accessStartTime, accessEndTime); + boolean result = handleAccessTimeCheck(user, accessStartTime, accessEndTime); + if (!result) { + throw new ServiceException("ip地址异常"); + }else{ + return; + } + } } + } @@ -312,27 +324,20 @@ public class PasswordValidatorService { * @param accessStartTime 访问开始时间 * @param accessEndTime 访问结束时间 */ - private void handleAccessTimeCheck(String accessStartTime, String accessEndTime) { + private boolean handleAccessTimeCheck(SysUser user, String accessStartTime, String accessEndTime) { if (ObjectUtils.isNotEmpty(accessStartTime)) { boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); if (!currentTimeInRange) { - handleException(); // 异常处理 + recordLogService.saveErrorLogs(user.getUserName(), System.currentTimeMillis(), user.getUserId().toString(),"IP地址异常"); + return false; } else { - handleNormalProcess(); // 正常处理 + return true; } } else { - handleNormalProcess(); // 正常处理 + return true; } } - /** - * 处理异常情况 - */ - private void handleException() { - // 异常处理的具体逻辑 - System.out.println("IP access is outside the allowed time range or other error occurred."); - } - /** * 处理正常情况 */ diff --git a/bonus-auth/src/main/java/com/bonus/auth/service/SysPasswordService.java b/bonus-auth/src/main/java/com/bonus/auth/service/SysPasswordService.java index 0a4cd04..b2bac6c 100644 --- a/bonus-auth/src/main/java/com/bonus/auth/service/SysPasswordService.java +++ b/bonus-auth/src/main/java/com/bonus/auth/service/SysPasswordService.java @@ -2,7 +2,6 @@ package com.bonus.auth.service; import com.bonus.common.core.constant.CacheConstants; import com.bonus.common.core.constant.Constants; -import com.bonus.common.core.constant.SecurityConstants; import com.bonus.common.core.domain.R; import com.bonus.common.core.exception.CaptchaException; import com.bonus.common.core.exception.ServiceException; @@ -57,8 +56,8 @@ public class SysPasswordService { Integer retryCount = redisService.getCacheObject(getCacheKey(username)); Integer times = 5; Integer lockTime = 20; - AjaxResult timesAjaxResult = configService.getConfigKey("sys.login.failed.times", SecurityConstants.INNER); - AjaxResult lockTimeAjaxResult = configService.getConfigKey("sys.login.failed.locktime", SecurityConstants.INNER); + AjaxResult timesAjaxResult = configService.getConfigKey("sys.login.failed.times"); + AjaxResult lockTimeAjaxResult = configService.getConfigKey("sys.login.failed.locktime"); if (timesAjaxResult.isSuccess()){ times = Integer.parseInt(timesAjaxResult.get("msg").toString()); } diff --git a/bonus-common/bonus-common-config/src/main/java/com/bonus/config/SystemConfig.java b/bonus-common/bonus-common-config/src/main/java/com/bonus/config/SystemConfig.java index 22c8775..7a5bdc4 100644 --- a/bonus-common/bonus-common-config/src/main/java/com/bonus/config/SystemConfig.java +++ b/bonus-common/bonus-common-config/src/main/java/com/bonus/config/SystemConfig.java @@ -48,7 +48,7 @@ public class SystemConfig { /** * websocketUrl */ - private String webSocketurl; + private String websocketurl; @Data @RefreshScope diff --git a/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/interceptor/ParamSecureHandler.java b/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/interceptor/ParamSecureHandler.java index e8be59c..7e0a2cf 100644 --- a/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/interceptor/ParamSecureHandler.java +++ b/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/interceptor/ParamSecureHandler.java @@ -25,7 +25,7 @@ import static org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE; public class ParamSecureHandler implements AsyncHandlerInterceptor { private static final String [] WHITE_URL = { - "/login", "/isAdmin", "/isLogin" ,"/register","/user/register","/operlog/addLogs","/job/edit","/user/resetPwd","/user/profile/updatePwd'"}; + "/login", "/isAdmin", "/isLogin" ,"/register","/user/register","/operlog/addLogs","/job/edit","/user/resetPwd","/user/profile/updatePwd","/user/confirmPassword"}; private String rnd = null; public static String ur = "/"; diff --git a/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/service/TokenService.java b/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/service/TokenService.java index fbec7af..be88e7b 100644 --- a/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/service/TokenService.java +++ b/bonus-common/bonus-common-security/src/main/java/com/bonus/common/security/service/TokenService.java @@ -1,5 +1,6 @@ package com.bonus.common.security.service; +import cn.hutool.core.util.ObjectUtil; import com.bonus.common.core.constant.CacheConstants; import com.bonus.common.core.constant.SecurityConstants; import com.bonus.common.core.utils.JwtUtils; @@ -11,6 +12,7 @@ import com.bonus.common.core.web.domain.AjaxResult; import com.bonus.common.redis.service.RedisService; import com.bonus.common.security.utils.SecurityUtils; import com.bonus.config.SystemConfig; +import com.bonus.system.api.RemoteConfigService; import com.bonus.system.api.RemoteUserService; import com.bonus.system.api.domain.SysUser; import com.bonus.system.api.model.LoginUser; @@ -81,8 +83,9 @@ public class TokenService { rspMap.put("access_token", accessToken); rspMap.put("expires_in", EXPIRETIME); rspMap.put("isLogin", isLogin(String.valueOf(userId))); + long tokenTime = getTokenTime(); //对token进行存储 - redisService.setCacheObject(LOGIN_USER_KEY + userId, token, systemConfig.getTokenTime(), TimeUnit.MINUTES); + redisService.setCacheObject(LOGIN_USER_KEY + userId, token, tokenTime, TimeUnit.MINUTES); SysUser sysUser = new SysUser(); sysUser.setUserId(loginUser.getSysUser().getUserId()); sysUser.setLoginDate(new Date()); @@ -187,14 +190,29 @@ public class TokenService { * @param loginUser 登录信息 */ public void refreshToken(LoginUser loginUser) { + long tokenTime = getTokenTime(); loginUser.setLoginTime(System.currentTimeMillis()); - loginUser.setExpireTime(loginUser.getLoginTime() + systemConfig.getTokenTime() * MILLIS_MINUTE); + loginUser.setExpireTime(loginUser.getLoginTime() + tokenTime * MILLIS_MINUTE); // 根据uuid将loginUser缓存 String userKey = getTokenKey(loginUser.getToken()); - redisService.setCacheObject(userKey, loginUser, systemConfig.getTokenTime(), TimeUnit.MINUTES); + redisService.setCacheObject(userKey, loginUser, tokenTime, TimeUnit.MINUTES); } private String getTokenKey(String token) { return ACCESS_TOKEN + token; } + + private Long getTokenTime(){ + long tokenTime = 20L; + String redisResult = redisService.getCacheObject("sys_config:"+ "sys.visit.tokentime"); + if(!redisResult.isEmpty()) { + tokenTime = Long.parseLong(redisResult); + }else { + Long result = systemConfig.getTokenTime(); + if (!ObjectUtil.isEmpty(result)){ + tokenTime = result; + } + } + return tokenTime; + } } diff --git a/bonus-gateway/src/main/java/com/bonus/gateway/filter/IpFilter.java b/bonus-gateway/src/main/java/com/bonus/gateway/filter/IpFilter.java index 5873e0e..bca2c53 100644 --- a/bonus-gateway/src/main/java/com/bonus/gateway/filter/IpFilter.java +++ b/bonus-gateway/src/main/java/com/bonus/gateway/filter/IpFilter.java @@ -1,95 +1,101 @@ -package com.bonus.gateway.filter; - -import com.bonus.common.core.constant.CacheConstants; -import com.bonus.common.redis.service.RedisService; - -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang3.ObjectUtils; -import org.springframework.cloud.gateway.filter.GatewayFilterChain; -import org.springframework.cloud.gateway.filter.GlobalFilter; -import org.springframework.core.Ordered; -import org.springframework.stereotype.Component; -import org.springframework.web.server.ServerWebExchange; -import reactor.core.publisher.Mono; - -import javax.annotation.Resource; -import java.net.InetAddress; -import java.net.UnknownHostException; -import java.time.LocalDateTime; -import java.time.format.DateTimeFormatter; -import java.util.List; -import java.util.Map; - -/** - * @author bonus - */ -@Component -@Slf4j -public class IpFilter implements GlobalFilter, Ordered { - @Resource - private RedisService redisService; - +//package com.bonus.gateway.filter; +// +//import com.bonus.common.core.constant.CacheConstants; +//import com.bonus.common.core.utils.DateUtils; +//import com.bonus.common.core.utils.SpringUtils; +//import com.bonus.common.core.utils.ip.IpUtils; +//import com.bonus.common.redis.service.RedisService; +// +//import com.bonus.system.api.RemoteLogService; +//import com.bonus.system.api.domain.SysLogsVo; +//import lombok.extern.slf4j.Slf4j; +//import org.apache.commons.lang3.ObjectUtils; +//import org.springframework.cloud.gateway.filter.GatewayFilterChain; +//import org.springframework.cloud.gateway.filter.GlobalFilter; +//import org.springframework.core.Ordered; +//import org.springframework.stereotype.Component; +//import org.springframework.web.server.ServerWebExchange; +//import reactor.core.publisher.Mono; +// +//import javax.annotation.Resource; +//import java.net.InetAddress; +//import java.net.UnknownHostException; +//import java.time.LocalDateTime; +//import java.time.format.DateTimeFormatter; +//import java.util.List; +//import java.util.Map; +//import java.util.UUID; +// +///** +// * @author bonus +// */ +//@Component +//@Slf4j +//public class IpFilter implements GlobalFilter, Ordered { // @Resource -// private RemoteLogService remoteLogService; -// public RemoteLogService remoteLogService = SpringUtils.getBean(RemoteLogService.class); - /** - * Process the Web request and (optionally) delegate to the next {@code GatewayFilter} - * through the given {@link GatewayFilterChain}. - * - * @param exchange the current server exchange - * @param chain provides a way to delegate to the next filter - * @return {@code Mono} to indicate when request processing is complete - */ - @Override - public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - List> cacheList = redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST); - - // 获取客户端的 IP 地址 - String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"); - for (Map map : cacheList) { - String ipAddress = map.containsKey("ipAddress") ? map.get("ipAddress").toString() : null; - String ipRangeEnd = map.containsKey("ipRangeEnd") ?map.get("ipRangeEnd").toString(): null; - String ipRangeStart = map.containsKey("ipRangeStart")?map.get("ipRangeStart").toString():null; - String accessStartTime =map.containsKey("accessStartTime")? map.get("accessStartTime").toString():null; - String accessEndTime = map.containsKey("accessEndTime")?map.get("accessEndTime").toString():null; - if (ObjectUtils.isEmpty(ipAddress)){ - if (isIpInRange(ip, ipRangeStart, ipRangeEnd)){ - if (ObjectUtils.isNotEmpty(accessStartTime)){ - boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); - if (!currentTimeInRange){ - // 完成响应 +// private RedisService redisService; +// +//// @Resource +//// private RemoteLogService remoteLogService; +//// public RemoteLogService remoteLogService = SpringUtils.getBean(RemoteLogService.class); +// /** +// * Process the Web request and (optionally) delegate to the next {@code GatewayFilter} +// * through the given {@link GatewayFilterChain}. +// * +// * @param exchange the current server exchange +// * @param chain provides a way to delegate to the next filter +// * @return {@code Mono} to indicate when request processing is complete +// */ +// @Override +// public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { +// List> cacheList = redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST); +// +// // 获取客户端的 IP 地址 +// String ip = exchange.getRequest().getHeaders().getFirst("X-Forwarded-For"); +// for (Map map : cacheList) { +// String ipAddress = map.containsKey("ipAddress") ? map.get("ipAddress").toString() : null; +// String ipRangeEnd = map.containsKey("ipRangeEnd") ?map.get("ipRangeEnd").toString(): null; +// String ipRangeStart = map.containsKey("ipRangeStart")?map.get("ipRangeStart").toString():null; +// String accessStartTime =map.containsKey("accessStartTime")? map.get("accessStartTime").toString():null; +// String accessEndTime = map.containsKey("accessEndTime")?map.get("accessEndTime").toString():null; +// if (ObjectUtils.isEmpty(ipAddress)){ +// if (isIpInRange(ip, ipRangeStart, ipRangeEnd)){ +// if (ObjectUtils.isNotEmpty(accessStartTime)){ +// boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); +// if (!currentTimeInRange){ +// // 完成响应 // handleLog(); - exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); - return exchange.getResponse().setComplete(); - }else { - return chain.filter(exchange); - } - }else { - return chain.filter(exchange); - } - - } - }else { - if (ipAddress.equals(ip)){ - if (ObjectUtils.isNotEmpty(accessStartTime)){ - boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); - if (!currentTimeInRange){ - // 完成响应 -// handleLog(); - exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); - return exchange.getResponse().setComplete(); - }else { - return chain.filter(exchange); - } - }else { - return chain.filter(exchange); - } - } - } - } - exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); - return exchange.getResponse().setComplete(); - } +// exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); +// return exchange.getResponse().setComplete(); +// }else { +// return chain.filter(exchange); +// } +// }else { +// return chain.filter(exchange); +// } +// +// } +// }else { +// if (ipAddress.equals(ip)){ +// if (ObjectUtils.isNotEmpty(accessStartTime)){ +// boolean currentTimeInRange = isCurrentTimeInRange(accessStartTime, accessEndTime); +// if (!currentTimeInRange){ +// // 完成响应 +//// handleLog(); +// exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); +// return exchange.getResponse().setComplete(); +// }else { +// return chain.filter(exchange); +// } +// }else { +// return chain.filter(exchange); +// } +// } +// } +// } +// exchange.getResponse().setStatusCode(org.springframework.http.HttpStatus.FORBIDDEN); +// return exchange.getResponse().setComplete(); +// } // private void handleLog() // { // SysLogsVo sysLogsVo = new SysLogsVo(); @@ -102,77 +108,77 @@ public class IpFilter implements GlobalFilter, Ordered { // sysLogsVo.setOperType("IP地址异常"); // sysLogsVo.setWarningStatus("0"); // try { -// remoteLogService.addLogs(sysLogsVo, SecurityConstants.INNER); +//// remoteLogService.addLogs(sysLogsVo, "inner"); // } catch (Exception e) { // throw new RuntimeException(e); // } // } - /** - * 检查给定的IP地址是否在指定的网段区间内 - * - * @param ip 要检查的IP地址,例如 "192.168.1.10" - * @param startIp 区间开始的IP地址,例如 "192.168.1.0" - * @param endIp 区间结束的IP地址,例如 "192.168.1.255" - * @return true 如果IP在区间内;否则返回 false - */ - public static boolean isIpInRange(String ip, String startIp, String endIp) { - try { - // 将 IP 地址、起始 IP 和结束 IP 转换为整数 - long ipToCheck = ipToLong(InetAddress.getByName(ip)); - long start = ipToLong(InetAddress.getByName(startIp)); - long end = ipToLong(InetAddress.getByName(endIp)); - - // 检查 IP 是否在区间内 - return ipToCheck >= start && ipToCheck <= end; - } catch (UnknownHostException e) { - e.printStackTrace(); - return false; - } - } - - /** - * 将IP地址转换为整数 - * - * @param inetAddress IP地址对象 - * @return 转换后的长整数 - */ - private static long ipToLong(InetAddress inetAddress) { - byte[] octets = inetAddress.getAddress(); - long result = 0; - for (byte octet : octets) { - result = (result << 8) | (octet & 0xFF); - } - return result; - } - public static boolean isCurrentTimeInRange(String startDateTime, String endDateTime) { - // 定义日期时间格式 - DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); - - // 将字符串转换为 LocalDateTime - LocalDateTime start = LocalDateTime.parse(startDateTime, formatter); - LocalDateTime end = LocalDateTime.parse(endDateTime, formatter); - - // 获取当前日期和时间 - LocalDateTime currentDateTime = LocalDateTime.now(); - - // 检查当前日期和时间是否在指定的范围内 - return !currentDateTime.isBefore(start) && !currentDateTime.isAfter(end); - } - - /** - * Get the order value of this object. - *

Higher values are interpreted as lower priority. As a consequence, - * the object with the lowest value has the highest priority (somewhat - * analogous to Servlet {@code load-on-startup} values). - *

Same order values will result in arbitrary sort positions for the - * affected objects. - * - * @return the order value - * @see #HIGHEST_PRECEDENCE - * @see #LOWEST_PRECEDENCE - */ - @Override - public int getOrder() { - return 0; - } -} +// /** +// * 检查给定的IP地址是否在指定的网段区间内 +// * +// * @param ip 要检查的IP地址,例如 "192.168.1.10" +// * @param startIp 区间开始的IP地址,例如 "192.168.1.0" +// * @param endIp 区间结束的IP地址,例如 "192.168.1.255" +// * @return true 如果IP在区间内;否则返回 false +// */ +// public static boolean isIpInRange(String ip, String startIp, String endIp) { +// try { +// // 将 IP 地址、起始 IP 和结束 IP 转换为整数 +// long ipToCheck = ipToLong(InetAddress.getByName(ip)); +// long start = ipToLong(InetAddress.getByName(startIp)); +// long end = ipToLong(InetAddress.getByName(endIp)); +// +// // 检查 IP 是否在区间内 +// return ipToCheck >= start && ipToCheck <= end; +// } catch (UnknownHostException e) { +// e.printStackTrace(); +// return false; +// } +// } +// +// /** +// * 将IP地址转换为整数 +// * +// * @param inetAddress IP地址对象 +// * @return 转换后的长整数 +// */ +// private static long ipToLong(InetAddress inetAddress) { +// byte[] octets = inetAddress.getAddress(); +// long result = 0; +// for (byte octet : octets) { +// result = (result << 8) | (octet & 0xFF); +// } +// return result; +// } +// public static boolean isCurrentTimeInRange(String startDateTime, String endDateTime) { +// // 定义日期时间格式 +// DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); +// +// // 将字符串转换为 LocalDateTime +// LocalDateTime start = LocalDateTime.parse(startDateTime, formatter); +// LocalDateTime end = LocalDateTime.parse(endDateTime, formatter); +// +// // 获取当前日期和时间 +// LocalDateTime currentDateTime = LocalDateTime.now(); +// +// // 检查当前日期和时间是否在指定的范围内 +// return !currentDateTime.isBefore(start) && !currentDateTime.isAfter(end); +// } +// +// /** +// * Get the order value of this object. +// *

Higher values are interpreted as lower priority. As a consequence, +// * the object with the lowest value has the highest priority (somewhat +// * analogous to Servlet {@code load-on-startup} values). +// *

Same order values will result in arbitrary sort positions for the +// * affected objects. +// * +// * @return the order value +// * @see #HIGHEST_PRECEDENCE +// * @see #LOWEST_PRECEDENCE +// */ +// @Override +// public int getOrder() { +// return 0; +// } +//} diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/BonusSystemApplication.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/BonusSystemApplication.java index bf6ff1a..4dd5244 100644 --- a/bonus-modules/bonus-system/src/main/java/com/bonus/system/BonusSystemApplication.java +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/BonusSystemApplication.java @@ -6,6 +6,7 @@ import com.bonus.common.security.annotation.EnableCustomConfig; import com.bonus.common.security.annotation.EnableRyFeignClients; import com.bonus.common.swagger.annotation.EnableCustomSwagger2; import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; +import org.springframework.scheduling.annotation.EnableScheduling; /** * 系统模块 @@ -16,6 +17,7 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration; @EnableCustomSwagger2 @EnableRyFeignClients @SpringBootApplication(exclude = { DataSourceAutoConfiguration.class }) +@EnableScheduling public class BonusSystemApplication { public static void main(String[] args) diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/controller/SysLogController.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/controller/SysLogController.java index b9ee4ad..2cceffa 100644 --- a/bonus-modules/bonus-system/src/main/java/com/bonus/system/controller/SysLogController.java +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/controller/SysLogController.java @@ -183,11 +183,12 @@ public class SysLogController extends BaseController { public R> getLogStatistics(@RequestBody SysLogsVo dto) { return service.getLogStatistics(dto); } - @ApiOperation(value = "查询日志告警") - @PostMapping("logWarn") - public R> logWarn() { - return service.logWarn(); - } + +// @ApiOperation(value = "查询日志告警") +// @PostMapping("logWarn") +// public R> logWarn() { +// return service.logWarn(); +// } } diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/ISysLogService.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/ISysLogService.java index 344b392..a0296bc 100644 --- a/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/ISysLogService.java +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/ISysLogService.java @@ -59,7 +59,7 @@ public interface ISysLogService { *日志容量告警 * @return */ - R> logWarn( ); + void logWarn( ); /** * 保存日志 diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysLogServiceImpl.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysLogServiceImpl.java index 73fc3fa..3079115 100644 --- a/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysLogServiceImpl.java +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysLogServiceImpl.java @@ -16,6 +16,7 @@ import com.bonus.common.core.utils.global.SystemGlobal; import com.bonus.system.api.domain.SysLogsVo; import com.bonus.system.api.model.LoginUser; import com.bonus.system.mapper.SysLogMapper; +import com.mysql.cj.xdevapi.Warning; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.scripting.xmltags.ForEachSqlNode; import org.springframework.beans.factory.annotation.Autowired; @@ -263,38 +264,22 @@ public class SysLogServiceImpl implements ISysLogService { * @return */ @Override - public R> logWarn() { - Map map=Maps.newHashMap(); - try { - double bfb=0.9; - //查询当日的告警 - int num =mapper.getErrorLogs(); - if(num>0){ - map.put("logWarn","1"); - map.put("err","您有新的异常告警"+num +",请及时处理!"); - }else{ - map.put("logWarn","0"); - } + public void logWarn() { + try { + double bfb=0.9; String rl=mapper.getLogsRl(); String city=mapper.getLogsSet(); Double d=Double.parseDouble(rl); Double max=Double.parseDouble(city)*bfb; if(d>=max){ - map.put("warnType","1"); - map.put("warnError","日志容量告警,当日日志内存为"+d+"MB,日志内存超过总内存的90%,请及时处理!"); - }else { - map.put("warnType","0"); + String warningEvent = "日志容量告警,当日日志内存为" +d+ "MB,日志内存超过总内存的90%,请及时处理!"; + eventPublisher.publishEvent(new WaringLogEvent(new SysWarning("0",warningEvent,"",null,null))); } - return R.ok(map); - }catch (Exception e){ - map.put("logWarn","0"); - map.put("warnType","0"); - log.error(e.toString(),e); - } - return R.ok(map); + }catch (Exception e){ + log.error(e.toString(),e); + } } - @Override @Async public void handleWarningLog(){ diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysOperLogServiceImpl.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysOperLogServiceImpl.java index 98186ef..f1ffee1 100644 --- a/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysOperLogServiceImpl.java +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/service/impl/SysOperLogServiceImpl.java @@ -104,7 +104,7 @@ public class SysOperLogServiceImpl implements ISysOperLogService public int addLogs(SysLogsVo sysLogsVo) { if (sysLogsVo.getLogType() == 2) { sysLogsVo.setWarningStatus("0"); - eventPublisher.publishEvent(new WaringLogEvent(new SysWarning(sysLogsVo.getLogId(), sysLogsVo.getOperType(), sysLogsVo.getIp(), sysLogsVo.getOperaUserName(), sysLogsVo.getOperTime()))); + eventPublisher.publishEvent(new WaringLogEvent(new SysWarning(sysLogsVo.getLogId(), sysLogsVo.getErrType(), sysLogsVo.getIp(), sysLogsVo.getOperaUserName(), sysLogsVo.getOperTime()))); } return operLogMapper.addLogs(sysLogsVo); } diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/ScheduledTasks.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/ScheduledTasks.java new file mode 100644 index 0000000..2a9992d --- /dev/null +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/ScheduledTasks.java @@ -0,0 +1,31 @@ +package com.bonus.system.warning; + +import com.bonus.system.service.ISysLogService; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import javax.annotation.Resource; +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +@Component +public class ScheduledTasks { + + private static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); + + @Resource(name = "ISysLogService") + private ISysLogService service; + + // 每5秒执行一次 + @Scheduled(fixedRate = 300000) + public void taskWithFixedRate() { + service.logWarn(); + System.out.println("数据库容量固定速率任务执行时间:" + LocalDateTime.now().format(formatter)); + } + +// // 每天凌晨1点执行 +// @Scheduled(cron = "0 */5 * * * ?") +// public void taskWithCron() { +// System.out.println("定时任务执行时间:" + LocalDateTime.now().format(formatter)); +// } +} \ No newline at end of file diff --git a/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/WebSocketConfig.java b/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/WebSocketConfig.java index 4ab86e2..ae7ca8b 100644 --- a/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/WebSocketConfig.java +++ b/bonus-modules/bonus-system/src/main/java/com/bonus/system/warning/WebSocketConfig.java @@ -12,6 +12,6 @@ import org.springframework.web.socket.config.annotation.*; public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { - registry.addHandler(new WebSocketHandler(), "/ws").setAllowedOrigins("*"); + registry.addHandler(new WebSocketHandler(), "/alert").setAllowedOrigins("*"); } } diff --git a/bonus-modules/bonus-system/src/main/resources/bootstrap.yml b/bonus-modules/bonus-system/src/main/resources/bootstrap.yml index db6b935..790dc0d 100644 --- a/bonus-modules/bonus-system/src/main/resources/bootstrap.yml +++ b/bonus-modules/bonus-system/src/main/resources/bootstrap.yml @@ -6,6 +6,11 @@ spring: profiles: # 环境配置 active: dev + task: + scheduling: + pool: + size: 1 # 定时任务线程池大小 + thread-name-prefix: scheduled-task- # 定时任务线程名称前缀 #加密组件 jasypt: diff --git a/sql/bns_20240604.sql b/sql/bns_20240604.sql index 18debeb..005cc27 100644 --- a/sql/bns_20240604.sql +++ b/sql/bns_20240604.sql @@ -64,12 +64,12 @@ create table sys_user ( login_type varchar(100) default null comment '登录类型', approval_status char(1) default '1' comment '审批状态0:未审批,1:已审批', is_permanent char(1) default '1' comment '长期和临时用户标识0:临时用户,1:长期用户', - is_built_in char(1) default '0' comment '是否内置用户0:非内置用户,1:内置用户', + is_built_in char(1) default '0' comment '是否内置用户0:内置用户,1:非内置用户', 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_user ADD is_built_in char(1) DEFAULT '1' 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 '邮箱'; @@ -80,8 +80,8 @@ ALTER TABLE `bns-cloud`.sys_user MODIFY COLUMN phonenumber varchar(255) CHARACTE -- ---------------------------- -- 初始化-用户信息表数据 -- ---------------------------- -insert into sys_user values(1, 103, 'bonus', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(), '系统管理员','0','1','1'); -insert into sys_user values(2, 103, 'audit', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(),'审计管理员','0','1','1'); +insert into sys_user values(1, 103, 'bonus', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(), '系统管理员','0','0','1'); +insert into sys_user values(2, 103, 'audit', '博诺思', '00', '38fb2b6be1e8b9024b0140fc673f0ed245b6b82ae6464387bbe806dc68e66fa8', '4eb762402e0ce5ef9d0028e2d622c53bc8ea1d7680ea4416975e4cc23b4ef7f0', '1', '', '$2a$10$5azz92OgGRyRUETz/ZJeZu1exkggPYUDRssvreywTjKk.0Pmn2Q16', '0', '0', '127.0.0.1', sysdate(), 'admin', sysdate(), '', null,sysdate(),'审计管理员','0','0','1'); -- ---------------------------- @@ -131,12 +131,12 @@ create table sys_role ( update_by varchar(64) default '' comment '更新者', update_time datetime comment '更新时间', remark varchar(500) default null comment '备注', - is_built_in char(1) default '0' comment '是否内置0:非内置,1:内置', + is_built_in char(1) default '0' comment '是否内置0:内置,1:非内置', 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:内置角色'; +ALTER TABLE `bns-cloud`.sys_role ADD is_built_in char(1) DEFAULT '1' NULL COMMENT '是否内置0:非内置角色,1:内置角色'; ---------------------- -- 初始化-角色信息表数据