fix(client): 设备移除逻辑与认证流程优化
- 修改设备移除时的本地清理方法,统一调用 clearLocalAuth - 优化设备数量限制校验逻辑,避免重复计算当前设备- 移除冗余的设备状态检查,简化设备移除流程- 调整 Redis 连接超时与等待时间,提升连接稳定性- 增强 MySQL 数据库连接配置,添加自动重连机制 -优化 Druid 连接池参数,提高数据库连接性能 - 简化客户端认证与数据上报逻辑,提升处理效率 - 移除过期设备状态更新逻辑,减少不必要的数据库操作- 调整慢 SQL 记录阈值,便于及时发现性能问题-优化版本分布与数据类型统计查询逻辑,提高响应速度
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
package com.ruoyi.web.controller.monitor;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
@@ -31,7 +32,7 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
import com.ruoyi.web.sse.SseHubService;
|
||||
import com.ruoyi.system.mapper.ClientDeviceMapper;
|
||||
import com.ruoyi.system.domain.ClientDevice;
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 客户端账号控制器
|
||||
@@ -139,36 +140,20 @@ public class ClientAccountController extends BaseController {
|
||||
if (!"0".equals(account.getStatus())) {
|
||||
return AjaxResult.error("账号已被停用");
|
||||
}
|
||||
|
||||
|
||||
// 检查设备数量限制
|
||||
String clientId = loginData.get("clientId");
|
||||
if (!StringUtils.isEmpty(clientId)) {
|
||||
ClientDevice currentDevice = clientDeviceMapper.selectByDeviceId(clientId);
|
||||
if (currentDevice == null || "removed".equals(currentDevice.getStatus())) {
|
||||
int deviceLimit = account.getDeviceLimit();
|
||||
java.util.List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
||||
int activeDeviceCount = 0;
|
||||
for (ClientDevice d : userDevices) {
|
||||
if (!"removed".equals(d.getStatus()) && !d.getDeviceId().equals(clientId)) {
|
||||
activeDeviceCount++;
|
||||
}
|
||||
}
|
||||
if (activeDeviceCount >= deviceLimit) {
|
||||
return AjaxResult.error("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
||||
}
|
||||
}
|
||||
int deviceLimit = account.getDeviceLimit();
|
||||
List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
||||
int userDevice = userDevices.size();
|
||||
boolean exists = userDevices.stream()
|
||||
.anyMatch(d -> clientId.equals(d.getDeviceId()));
|
||||
if(exists)userDevice--;
|
||||
if (userDevice >= deviceLimit) {
|
||||
return AjaxResult.error("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
||||
}
|
||||
|
||||
String accessToken = Jwts.builder()
|
||||
.setHeaderParam("kid", jwtRsaKeyService.getKeyId())
|
||||
.setSubject(username)
|
||||
.setIssuedAt(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
|
||||
.claim("accountId", account.getId())
|
||||
.claim("username", username)
|
||||
.claim("clientId", clientId)
|
||||
.signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey())
|
||||
.compact();
|
||||
|
||||
String accessToken = Jwts.builder().setHeaderParam("kid", jwtRsaKeyService.getKeyId()).setSubject(username).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION)).claim("accountId", account.getId()).claim("username", username).claim("clientId", clientId).signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey()).compact();
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("accessToken", accessToken);
|
||||
result.put("permissions", account.getPermissions());
|
||||
@@ -176,9 +161,7 @@ public class ClientAccountController extends BaseController {
|
||||
result.put("expireTime", account.getExpireTime());
|
||||
return AjaxResult.success("登录成功", result);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 验证token
|
||||
@@ -207,7 +190,7 @@ public class ClientAccountController extends BaseController {
|
||||
} else {
|
||||
result.put("isVip", false);
|
||||
}
|
||||
|
||||
|
||||
return AjaxResult.success("验证成功", result);
|
||||
}
|
||||
|
||||
@@ -224,7 +207,10 @@ public class ClientAccountController extends BaseController {
|
||||
}
|
||||
|
||||
SseEmitter emitter = sseHubService.register(username, clientId, 0L);
|
||||
try { emitter.send(SseEmitter.event().data("{\"type\":\"ready\"}")); } catch (Exception ignored) {}
|
||||
try {
|
||||
emitter.send(SseEmitter.event().data("{\"type\":\"ready\"}"));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return emitter;
|
||||
}
|
||||
|
||||
@@ -244,7 +230,7 @@ public class ClientAccountController extends BaseController {
|
||||
clientAccount.setStatus("0");
|
||||
clientAccount.setPermissions("{\"amazon\":true,\"rakuten\":true,\"zebra\":true}");
|
||||
clientAccount.setPassword(passwordEncoder.encode(password));
|
||||
|
||||
|
||||
// 检查设备ID是否已注册过(赠送VIP逻辑)
|
||||
boolean isNewDevice = true;
|
||||
if (!StringUtils.isEmpty(deviceId)) {
|
||||
@@ -257,28 +243,20 @@ public class ClientAccountController extends BaseController {
|
||||
} else {
|
||||
vipDays = 0; // 立即过期,需要续费
|
||||
}
|
||||
|
||||
|
||||
if (vipDays > 0) {
|
||||
Date expireDate = new Date(System.currentTimeMillis() + vipDays * 24L * 60 * 60 * 1000);
|
||||
clientAccount.setExpireTime(expireDate);
|
||||
} else {
|
||||
clientAccount.setExpireTime(new Date());
|
||||
}
|
||||
|
||||
|
||||
int result = clientAccountService.insertClientAccount(clientAccount);
|
||||
if (result <= 0) {
|
||||
return AjaxResult.error("注册失败");
|
||||
}
|
||||
|
||||
String accessToken = Jwts.builder()
|
||||
.setHeaderParam("kid", jwtRsaKeyService.getKeyId())
|
||||
.setSubject(clientAccount.getUsername())
|
||||
.setIssuedAt(new Date())
|
||||
.setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION))
|
||||
.claim("accountId", clientAccount.getId())
|
||||
.claim("clientId", deviceId)
|
||||
.signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey())
|
||||
.compact();
|
||||
|
||||
String accessToken = Jwts.builder().setHeaderParam("kid", jwtRsaKeyService.getKeyId()).setSubject(clientAccount.getUsername()).setIssuedAt(new Date()).setExpiration(new Date(System.currentTimeMillis() + JWT_EXPIRATION)).claim("accountId", clientAccount.getId()).claim("clientId", deviceId).signWith(SignatureAlgorithm.RS256, jwtRsaKeyService.getPrivateKey()).compact();
|
||||
|
||||
Map<String, Object> dataMap = new HashMap<>();
|
||||
dataMap.put("accessToken", accessToken);
|
||||
@@ -309,12 +287,12 @@ public class ClientAccountController extends BaseController {
|
||||
public AjaxResult renew(@RequestBody Map<String, Object> data) {
|
||||
Long accountId = Long.valueOf(data.get("accountId").toString());
|
||||
Integer days = Integer.valueOf(data.get("days").toString());
|
||||
|
||||
|
||||
ClientAccount account = clientAccountService.selectClientAccountById(accountId);
|
||||
if (account == null) {
|
||||
return AjaxResult.error("账号不存在");
|
||||
}
|
||||
|
||||
|
||||
java.util.Calendar cal = java.util.Calendar.getInstance();
|
||||
if (account.getExpireTime() != null && account.getExpireTime().after(new Date())) {
|
||||
cal.setTime(account.getExpireTime());
|
||||
@@ -323,20 +301,19 @@ public class ClientAccountController extends BaseController {
|
||||
}
|
||||
cal.add(java.util.Calendar.DAY_OF_MONTH, days);
|
||||
Date newExpireTime = cal.getTime();
|
||||
|
||||
|
||||
account.setExpireTime(newExpireTime);
|
||||
account.setUpdateBy(getUsername());
|
||||
clientAccountService.updateClientAccount(account);
|
||||
|
||||
|
||||
// 通过SSE推送续费通知给该账号的所有在线设备
|
||||
try {
|
||||
sseHubService.sendEventToAllDevices(account.getUsername(), "VIP_RENEWED",
|
||||
"{\"expireTime\":\"" + newExpireTime + "\"}");
|
||||
sseHubService.sendEventToAllDevices(account.getUsername(), "VIP_RENEWED", "{\"expireTime\":\"" + newExpireTime + "\"}");
|
||||
} catch (Exception e) {
|
||||
// SSE推送失败不影响续费操作
|
||||
}
|
||||
|
||||
|
||||
return AjaxResult.success("续费成功,新的过期时间:" + newExpireTime);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -26,7 +26,8 @@ public class VersionController extends BaseController {
|
||||
@Autowired
|
||||
private RedisTemplate<String, String> redisTemplate;
|
||||
private static final String VERSION_REDIS_KEY = "erp:client:version";
|
||||
private static final String DOWNLOAD_URL_REDIS_KEY = "erp:client:url";
|
||||
private static final String ASAR_URL_REDIS_KEY = "erp:client:asar_url";
|
||||
private static final String JAR_URL_REDIS_KEY = "erp:client:jar_url";
|
||||
|
||||
/**
|
||||
* 检查版本更新
|
||||
@@ -44,8 +45,12 @@ public class VersionController extends BaseController {
|
||||
result.put("latestVersion", latestVersion);
|
||||
result.put("needUpdate", needUpdate);
|
||||
// 从Redis获取下载链接
|
||||
String downloadUrl = redisTemplate.opsForValue().get(DOWNLOAD_URL_REDIS_KEY);
|
||||
result.put("downloadUrl", downloadUrl);
|
||||
String asarUrl = redisTemplate.opsForValue().get(ASAR_URL_REDIS_KEY);
|
||||
String jarUrl = redisTemplate.opsForValue().get(JAR_URL_REDIS_KEY);
|
||||
result.put("asarUrl", asarUrl);
|
||||
result.put("jarUrl", jarUrl);
|
||||
// 兼容旧版本,保留downloadUrl字段(指向asar)
|
||||
result.put("downloadUrl", asarUrl);
|
||||
|
||||
return AjaxResult.success(result);
|
||||
} catch (Exception e) {
|
||||
@@ -63,11 +68,13 @@ public class VersionController extends BaseController {
|
||||
if (StringUtils.isEmpty(currentVersion)) {
|
||||
currentVersion = "2.0.0";
|
||||
}
|
||||
String downloadUrl = redisTemplate.opsForValue().get(DOWNLOAD_URL_REDIS_KEY);
|
||||
String asarUrl = redisTemplate.opsForValue().get(ASAR_URL_REDIS_KEY);
|
||||
String jarUrl = redisTemplate.opsForValue().get(JAR_URL_REDIS_KEY);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("currentVersion", currentVersion);
|
||||
result.put("downloadUrl", downloadUrl);
|
||||
result.put("asarUrl", asarUrl);
|
||||
result.put("jarUrl", jarUrl);
|
||||
result.put("updateTime", System.currentTimeMillis());
|
||||
|
||||
return AjaxResult.success(result);
|
||||
@@ -83,13 +90,20 @@ public class VersionController extends BaseController {
|
||||
@PreAuthorize("@ss.hasPermi('system:version:update')")
|
||||
@PostMapping("/update")
|
||||
public AjaxResult updateVersionInfo(@RequestParam("version") String version,
|
||||
@RequestParam("downloadUrl") String downloadUrl) {
|
||||
@RequestParam(value = "asarUrl", required = false) String asarUrl,
|
||||
@RequestParam(value = "jarUrl", required = false) String jarUrl) {
|
||||
try {
|
||||
redisTemplate.opsForValue().set(VERSION_REDIS_KEY, version);
|
||||
redisTemplate.opsForValue().set(DOWNLOAD_URL_REDIS_KEY, downloadUrl);
|
||||
if (StringUtils.isNotEmpty(asarUrl)) {
|
||||
redisTemplate.opsForValue().set(ASAR_URL_REDIS_KEY, asarUrl);
|
||||
}
|
||||
if (StringUtils.isNotEmpty(jarUrl)) {
|
||||
redisTemplate.opsForValue().set(JAR_URL_REDIS_KEY, jarUrl);
|
||||
}
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("version", version);
|
||||
result.put("downloadUrl", downloadUrl);
|
||||
result.put("asarUrl", asarUrl);
|
||||
result.put("jarUrl", jarUrl);
|
||||
result.put("updateTime", System.currentTimeMillis());
|
||||
return AjaxResult.success("版本信息更新成功", result);
|
||||
} catch (Exception e) {
|
||||
@@ -107,7 +121,6 @@ public class VersionController extends BaseController {
|
||||
if (StringUtils.isEmpty(version1) || StringUtils.isEmpty(version2)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
String[] v1Parts = version1.split("\\.");
|
||||
String[] v2Parts = version2.split("\\.");
|
||||
|
||||
|
||||
@@ -53,15 +53,10 @@ public class ClientDeviceController {
|
||||
private void checkDeviceLimit(String username, String currentDeviceId) {
|
||||
int deviceLimit = getDeviceLimit(username);
|
||||
List<ClientDevice> userDevices = clientDeviceMapper.selectByUsername(username);
|
||||
int activeDeviceCount = 0;
|
||||
for (ClientDevice d : userDevices) {
|
||||
if (!"removed".equals(d.getStatus()) && !d.getDeviceId().equals(currentDeviceId)) {
|
||||
activeDeviceCount++;
|
||||
}
|
||||
}
|
||||
if (activeDeviceCount >= deviceLimit) {
|
||||
if (userDevices.size() >= deviceLimit) {
|
||||
throw new RuntimeException("设备数量已达上限(" + deviceLimit + "个),请先移除其他设备");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -157,14 +152,11 @@ public class ClientDeviceController {
|
||||
return AjaxResult.success();
|
||||
}
|
||||
if (!"removed".equals(exists.getStatus())) {
|
||||
// 先推送下线事件,再断开连接
|
||||
sseHubService.sendEvent(exists.getUsername(), deviceId, "DEVICE_REMOVED", "{}");
|
||||
// 立即断开SSE连接,防止重新上线
|
||||
sseHubService.disconnectDevice(exists.getUsername(), deviceId);
|
||||
// 更新设备状态
|
||||
exists.setStatus("removed");
|
||||
exists.setLastActiveAt(new java.util.Date());
|
||||
clientDeviceMapper.updateByDeviceId(exists);
|
||||
sseHubService.sendEvent(exists.getUsername(), deviceId, "DEVICE_REMOVED", "{}");
|
||||
sseHubService.disconnectDevice(exists.getUsername(), deviceId);
|
||||
}
|
||||
return AjaxResult.success();
|
||||
}
|
||||
@@ -175,13 +167,11 @@ public class ClientDeviceController {
|
||||
@PostMapping("/offline")
|
||||
public AjaxResult offline(@RequestBody Map<String, String> body) {
|
||||
String deviceId = body.get("deviceId");
|
||||
if (deviceId == null) return AjaxResult.error("deviceId不能为空");
|
||||
ClientDevice device = clientDeviceMapper.selectByDeviceId(deviceId);
|
||||
if (device != null) {
|
||||
device.setStatus("offline");
|
||||
device.setLastActiveAt(new java.util.Date());
|
||||
clientDeviceMapper.updateByDeviceId(device);
|
||||
}
|
||||
|
||||
return AjaxResult.success();
|
||||
}
|
||||
|
||||
@@ -198,13 +188,7 @@ public class ClientDeviceController {
|
||||
String os = device.getOs();
|
||||
String deviceName = username + "@" + ip + " (" + os + ")";
|
||||
|
||||
// 统一检查设备数量限制
|
||||
try {
|
||||
checkDeviceLimit(device.getUsername(), device.getDeviceId());
|
||||
} catch (RuntimeException e) {
|
||||
return AjaxResult.error(e.getMessage());
|
||||
}
|
||||
|
||||
|
||||
if (exists == null) {
|
||||
// 新设备注册
|
||||
device.setIp(ip);
|
||||
|
||||
@@ -42,7 +42,6 @@ public class FileController {
|
||||
|
||||
@PostMapping("/uploads")
|
||||
public AjaxResult uploadFiles(@RequestParam("files") List<MultipartFile> files) {
|
||||
|
||||
List<FileDto> fileDtoS = new ArrayList<>();
|
||||
for (MultipartFile file : files) {
|
||||
String extName = FileUtil.extName(file.getOriginalFilename());
|
||||
|
||||
@@ -11,11 +11,6 @@ import com.ruoyi.system.domain.*;
|
||||
*/
|
||||
public interface IClientMonitorService {
|
||||
|
||||
/**
|
||||
* 查询客户端设备列表
|
||||
*/
|
||||
List<ClientDevice> selectClientDeviceList(String username);
|
||||
|
||||
/**
|
||||
* 查询客户端错误报告列表
|
||||
*/
|
||||
@@ -31,36 +26,11 @@ public interface IClientMonitorService {
|
||||
*/
|
||||
List<ClientDataReport> selectClientDataReportList(ClientDataReport clientDataReport);
|
||||
|
||||
/**
|
||||
* 查询在线客户端数量
|
||||
*/
|
||||
int selectOnlineClientCount();
|
||||
|
||||
/**
|
||||
* 检查客户端是否在线
|
||||
*/
|
||||
boolean isClientOnline(String clientId);
|
||||
|
||||
/**
|
||||
* 获取在线客户端ID列表
|
||||
*/
|
||||
List<String> getOnlineClientIds();
|
||||
|
||||
/**
|
||||
* 查询客户端总数
|
||||
*/
|
||||
int selectTotalClientCount();
|
||||
|
||||
/**
|
||||
* 获取客户端统计数据
|
||||
*/
|
||||
Map<String, Object> getClientStatistics();
|
||||
|
||||
/**
|
||||
* 获取客户端活跃趋势
|
||||
*/
|
||||
Map<String, Object> getClientActiveTrend();
|
||||
|
||||
/**
|
||||
* 获取数据采集类型分布
|
||||
*/
|
||||
@@ -96,26 +66,6 @@ public interface IClientMonitorService {
|
||||
*/
|
||||
List<Map<String, Object>> getVersionDistribution();
|
||||
|
||||
/**
|
||||
* 插入客户端错误报告
|
||||
*/
|
||||
int insertClientError(ClientErrorReport clientErrorReport);
|
||||
|
||||
/**
|
||||
* 插入客户端设备
|
||||
*/
|
||||
int insertClientDevice(ClientDevice clientDevice);
|
||||
|
||||
/**
|
||||
* 插入客户端事件日志
|
||||
*/
|
||||
int insertClientEventLog(ClientEventLog clientEventLog);
|
||||
|
||||
/**
|
||||
* 插入数据报告
|
||||
*/
|
||||
int insertDataReport(ClientDataReport clientDataReport);
|
||||
|
||||
/**
|
||||
* 查询客户端信息列表
|
||||
*/
|
||||
|
||||
@@ -1,26 +1,14 @@
|
||||
package com.ruoyi.web.service.impl;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicLong;
|
||||
|
||||
import java.util.*;
|
||||
import com.ruoyi.system.domain.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import javax.annotation.PreDestroy;
|
||||
import com.ruoyi.common.utils.DateUtils;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.ruoyi.web.service.IClientAccountService;
|
||||
import com.ruoyi.web.service.IClientMonitorService;
|
||||
import com.ruoyi.system.mapper.ClientMonitorMapper;
|
||||
import com.ruoyi.system.mapper.ClientDeviceMapper;
|
||||
|
||||
/**
|
||||
* 客户端监控服务实现
|
||||
@@ -35,42 +23,11 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
@Autowired
|
||||
private ClientMonitorMapper clientMonitorMapper;
|
||||
|
||||
@Autowired
|
||||
private ClientDeviceMapper clientDeviceMapper;
|
||||
|
||||
@Autowired
|
||||
private IClientAccountService clientAccountService;
|
||||
|
||||
|
||||
// 线程池用于异步处理日志记录
|
||||
private final ExecutorService logExecutor = new ThreadPoolExecutor(
|
||||
2, 4, 60L, TimeUnit.SECONDS,
|
||||
new LinkedBlockingQueue<>(100),
|
||||
new ThreadPoolExecutor.CallerRunsPolicy()
|
||||
);
|
||||
|
||||
// API调用计数器,减少频繁日志记录
|
||||
private final AtomicLong apiCallCounter = new AtomicLong(0);
|
||||
|
||||
/**
|
||||
* 查询设备列表 - 基于ClientDevice表
|
||||
*/
|
||||
@Override
|
||||
public List<ClientDevice> selectClientDeviceList(String username) {
|
||||
logApiCallAsync("selectClientDeviceList", null);
|
||||
if (username != null && !username.isEmpty()) {
|
||||
return clientDeviceMapper.selectByUsername(username);
|
||||
} else {
|
||||
return clientMonitorMapper.selectOnlineDevices();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询客户端错误报告列表
|
||||
*/
|
||||
@Override
|
||||
public List<Map<String, Object>> selectClientErrorList(ClientErrorReport clientErrorReport) {
|
||||
logApiCallAsync("selectClientErrorList", null);
|
||||
return clientMonitorMapper.selectClientErrorList(clientErrorReport);
|
||||
}
|
||||
|
||||
@@ -79,7 +36,6 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
*/
|
||||
@Override
|
||||
public List<ClientEventLog> selectClientEventLogList(ClientEventLog clientEventLog) {
|
||||
logApiCallAsync("selectClientEventLogList", null);
|
||||
return clientMonitorMapper.selectClientEventLogList(clientEventLog);
|
||||
}
|
||||
|
||||
@@ -88,136 +44,53 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
*/
|
||||
@Override
|
||||
public List<ClientDataReport> selectClientDataReportList(ClientDataReport clientDataReport) {
|
||||
logApiCallAsync("selectClientDataReportList", null);
|
||||
return clientMonitorMapper.selectClientDataReportList(clientDataReport);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询在线客户端数量 - 基于数据库
|
||||
*/
|
||||
@Override
|
||||
public int selectOnlineClientCount() {
|
||||
logApiCallAsync("selectOnlineClientCount", null);
|
||||
return clientMonitorMapper.selectOnlineClientCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查客户端是否在线 - 基于数据库
|
||||
*/
|
||||
@Override
|
||||
public boolean isClientOnline(String clientId) {
|
||||
if (clientId == null || clientId.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
ClientInfo clientInfo = clientMonitorMapper.selectClientInfoByClientId(clientId);
|
||||
return clientInfo != null && "1".equals(clientInfo.getOnline());
|
||||
} catch (Exception e) {
|
||||
System.err.println("检查客户端在线状态失败: " + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取在线客户端列表 - 基于数据库
|
||||
*/
|
||||
@Override
|
||||
public List<String> getOnlineClientIds() {
|
||||
try {
|
||||
ClientInfo queryParam = new ClientInfo();
|
||||
queryParam.setOnline("1");
|
||||
List<ClientInfo> onlineClients = clientMonitorMapper.selectClientInfoList(queryParam);
|
||||
List<String> onlineClientIds = new ArrayList<>();
|
||||
for (ClientInfo client : onlineClients) {
|
||||
onlineClientIds.add(client.getClientId());
|
||||
}
|
||||
return onlineClientIds;
|
||||
} catch (Exception e) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询客户端总数
|
||||
*/
|
||||
@Override
|
||||
public int selectTotalClientCount() {
|
||||
logApiCallAsync("selectTotalClientCount", null);
|
||||
return clientMonitorMapper.selectTotalClientCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端统计数据
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> getClientStatistics() {
|
||||
Map<String, Object> statistics = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 基础统计数据
|
||||
int totalClients = clientMonitorMapper.selectTotalClientCount();
|
||||
int onlineClients = selectOnlineClientCount(); // 使用Redis优化的方法
|
||||
int onlineClients = clientMonitorMapper.selectOnlineClientCount();
|
||||
int errorCount = clientMonitorMapper.selectTodayErrorCount();
|
||||
int todayDataCount = clientMonitorMapper.selectTodayDataCount();
|
||||
|
||||
// 构建返回数据
|
||||
statistics.put("totalClients", totalClients);
|
||||
statistics.put("onlineClients", onlineClients);
|
||||
statistics.put("errorCount", errorCount);
|
||||
statistics.put("todayDataCount", todayDataCount);
|
||||
// 计算错误率
|
||||
|
||||
double errorRate = (todayDataCount > 0) ? (errorCount * 100.0 / todayDataCount) : 0;
|
||||
statistics.put("errorRate", Math.round(errorRate * 10) / 10.0);
|
||||
|
||||
} catch (Exception e) {
|
||||
// 查询失败时返回默认值
|
||||
statistics.put("totalClients", 0);
|
||||
statistics.put("onlineClients", 0);
|
||||
statistics.put("errorCount", 0);
|
||||
statistics.put("todayDataCount", 0);
|
||||
statistics.put("errorRate", 0.0);
|
||||
}
|
||||
|
||||
// 异步记录API调用日志,减少阻塞
|
||||
logApiCallAsync("getClientStatistics", null);
|
||||
|
||||
return statistics;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端新增趋势 - 近7天每日新注册用户数量
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> getClientActiveTrend() {
|
||||
// 使用新增用户趋势数据
|
||||
return getOnlineClientTrend();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据采集类型分布
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> getDataTypeDistribution() {
|
||||
Map<String, Object> distribution = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 异步查询数据类型分布,设置2秒超时
|
||||
CompletableFuture<List<Map<String, Object>>> distributionFuture = CompletableFuture
|
||||
.supplyAsync(() -> clientMonitorMapper.selectDataTypeDistribution(), logExecutor);
|
||||
|
||||
List<Map<String, Object>> dataTypeList = distributionFuture.get(2, TimeUnit.SECONDS);
|
||||
|
||||
// 将查询结果转换为前端需要的格式
|
||||
List<Map<String, Object>> dataTypeList = clientMonitorMapper.selectDataTypeDistribution();
|
||||
for (Map<String, Object> item : dataTypeList) {
|
||||
String dataType = (String) item.get("dataType");
|
||||
Object count = item.get("count");
|
||||
|
||||
if (dataType != null) {
|
||||
// 根据数据类型设置对应的键名
|
||||
if ("ORDER".equalsIgnoreCase(dataType) || "BANMA".equalsIgnoreCase(dataType)) {
|
||||
// 将ORDER和BANMA都作为orderCount
|
||||
if (distribution.containsKey("orderCount")) {
|
||||
// 如果已经存在,则累加
|
||||
int existingCount = Integer.parseInt(distribution.get("orderCount").toString());
|
||||
int newCount = Integer.parseInt(count.toString());
|
||||
distribution.put("orderCount", existingCount + newCount);
|
||||
@@ -229,7 +102,6 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
} else if ("AMAZON".equalsIgnoreCase(dataType)) {
|
||||
distribution.put("amazonCount", count);
|
||||
} else {
|
||||
// 其他类型的数据,使用dataType + "Count"作为键名
|
||||
distribution.put(dataType.toLowerCase() + "Count", count);
|
||||
}
|
||||
}
|
||||
@@ -237,23 +109,15 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
} catch (Exception e) {
|
||||
}
|
||||
|
||||
// 确保必要的键存在
|
||||
if (!distribution.containsKey("orderCount")) {
|
||||
distribution.put("orderCount", 0);
|
||||
}
|
||||
if (!distribution.containsKey("rakutenCount")) {
|
||||
distribution.put("rakutenCount", 0);
|
||||
}
|
||||
if (!distribution.containsKey("amazonCount")) {
|
||||
distribution.put("amazonCount", 0);
|
||||
}
|
||||
distribution.putIfAbsent("orderCount", 0);
|
||||
distribution.putIfAbsent("rakutenCount", 0);
|
||||
distribution.putIfAbsent("amazonCount", 0);
|
||||
|
||||
logApiCallAsync("getDataTypeDistribution", null);
|
||||
return distribution;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取近7天新增客户端趋势 - 基于认证时间统计每日新注册用户
|
||||
* 获取近7天新增客户端趋势
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> getOnlineClientTrend() {
|
||||
@@ -262,7 +126,6 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
List<Integer> counts = new ArrayList<>();
|
||||
|
||||
try {
|
||||
// 使用数据库查询获取近7天客户端活跃趋势
|
||||
List<Map<String, Object>> activeTrendData = clientMonitorMapper.selectClientActiveTrend();
|
||||
|
||||
if (activeTrendData != null && !activeTrendData.isEmpty()) {
|
||||
@@ -270,60 +133,43 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
String dateStr = (String) dayData.get("date");
|
||||
Integer count = ((Number) dayData.get("count")).intValue();
|
||||
|
||||
// 转换日期格式从 yyyy-MM-dd 到 MM/dd
|
||||
String[] dateParts = dateStr.split("-");
|
||||
if (dateParts.length == 3) {
|
||||
String formattedDate = String.format("%02d/%02d",
|
||||
dates.add(String.format("%02d/%02d",
|
||||
Integer.parseInt(dateParts[1]),
|
||||
Integer.parseInt(dateParts[2]));
|
||||
dates.add(formattedDate);
|
||||
Integer.parseInt(dateParts[2])));
|
||||
} else {
|
||||
dates.add(dateStr);
|
||||
}
|
||||
|
||||
counts.add(count);
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有数据,生成默认的7天数据
|
||||
if (dates.isEmpty()) {
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
for (int i = 6; i >= 0; i--) {
|
||||
calendar.setTime(new Date());
|
||||
calendar.add(Calendar.DAY_OF_MONTH, -i);
|
||||
|
||||
String dateStr = String.format("%02d/%02d",
|
||||
calendar.get(Calendar.MONTH) + 1,
|
||||
calendar.get(Calendar.DAY_OF_MONTH));
|
||||
dates.add(dateStr);
|
||||
counts.add(0);
|
||||
}
|
||||
generateDefaultTrendData(dates, counts);
|
||||
}
|
||||
|
||||
trend.put("dates", dates);
|
||||
trend.put("counts", counts);
|
||||
} catch (Exception e) {
|
||||
// 异常时返回默认的7天数据
|
||||
dates.clear();
|
||||
counts.clear();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
for (int i = 6; i >= 0; i--) {
|
||||
calendar.setTime(new Date());
|
||||
calendar.add(Calendar.DAY_OF_MONTH, -i);
|
||||
|
||||
String dateStr = String.format("%02d/%02d",
|
||||
calendar.get(Calendar.MONTH) + 1,
|
||||
calendar.get(Calendar.DAY_OF_MONTH));
|
||||
dates.add(dateStr);
|
||||
counts.add(0);
|
||||
}
|
||||
trend.put("dates", dates);
|
||||
trend.put("counts", counts);
|
||||
generateDefaultTrendData(dates, counts);
|
||||
}
|
||||
|
||||
logApiCallAsync("getOnlineClientTrend", null);
|
||||
trend.put("dates", dates);
|
||||
trend.put("counts", counts);
|
||||
return trend;
|
||||
}
|
||||
|
||||
private void generateDefaultTrendData(List<String> dates, List<Integer> counts) {
|
||||
dates.clear();
|
||||
counts.clear();
|
||||
Calendar calendar = Calendar.getInstance();
|
||||
for (int i = 6; i >= 0; i--) {
|
||||
calendar.setTime(new Date());
|
||||
calendar.add(Calendar.DAY_OF_MONTH, -i);
|
||||
dates.add(String.format("%02d/%02d",
|
||||
calendar.get(Calendar.MONTH) + 1,
|
||||
calendar.get(Calendar.DAY_OF_MONTH)));
|
||||
counts.add(0);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端认证
|
||||
@@ -332,26 +178,11 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
public Map<String, Object> authenticateClient(String authKey, Map<String, Object> clientInfo) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
// TODO
|
||||
|
||||
// 生成访问令牌
|
||||
String accessToken = generateAccessToken();
|
||||
|
||||
// 获取客户端传来的clientId
|
||||
String clientIdFromClient = (String) clientInfo.get("clientId");
|
||||
|
||||
// 根据clientId查找现有客户端
|
||||
ClientInfo existingClient = findClientByClientId(clientIdFromClient);
|
||||
|
||||
String clientId;
|
||||
String username;
|
||||
String accessToken = UUID.randomUUID().toString().replace("-", "");
|
||||
String clientId = (String) clientInfo.get("clientId");
|
||||
|
||||
ClientInfo existingClient = findClientByClientId(clientId);
|
||||
if (existingClient != null) {
|
||||
// 重用已有客户端ID和用户名
|
||||
clientId = existingClient.getClientId();
|
||||
username = existingClient.getUsername();
|
||||
|
||||
// 更新现有客户端信息
|
||||
existingClient.setAccessToken(accessToken);
|
||||
existingClient.setOsName((String) clientInfo.get("osName"));
|
||||
existingClient.setOsVersion((String) clientInfo.get("osVersion"));
|
||||
@@ -361,35 +192,20 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
existingClient.setLastActiveTime(DateUtils.getNowDate());
|
||||
existingClient.setOnline("1");
|
||||
clientMonitorMapper.updateClientOnlineStatus(clientId, "1");
|
||||
} else {
|
||||
clientId = clientIdFromClient;
|
||||
username = (String) clientInfo.getOrDefault("username", "user");
|
||||
}
|
||||
|
||||
|
||||
|
||||
// 获取权限配置 - 暂时设为空,后续根据账号体系实现
|
||||
String permissions = null;
|
||||
|
||||
// 返回标准格式
|
||||
result.put("success", true);
|
||||
result.put("accessToken", accessToken);
|
||||
result.put("tokenType", "Bearer");
|
||||
result.put("expiresIn", 7200); // 2小时过期
|
||||
result.put("expiresIn", 7200);
|
||||
result.put("clientId", clientId);
|
||||
result.put("permissions", permissions); // 添加权限配置
|
||||
|
||||
result.put("permissions", null);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
throw new RuntimeException("认证过程中出现错误: " + e.getMessage());
|
||||
throw new RuntimeException("认证失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找IP地址对应的客户端
|
||||
*/
|
||||
private ClientInfo findClientByClientId(String clientId) {
|
||||
if (clientId == null || clientId.isEmpty()) {
|
||||
return null;
|
||||
@@ -398,47 +214,11 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
ClientInfo queryParams = new ClientInfo();
|
||||
queryParams.setClientId(clientId);
|
||||
List<ClientInfo> clients = clientMonitorMapper.selectClientInfoList(queryParams);
|
||||
|
||||
return clients != null && !clients.isEmpty() ? clients.get(0) : null;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private ClientInfo findClientByIp(String ipAddress) {
|
||||
if (ipAddress == null || ipAddress.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
ClientInfo queryParams = new ClientInfo();
|
||||
queryParams.setIpAddress(ipAddress);
|
||||
List<ClientInfo> clients = clientMonitorMapper.selectClientInfoList(queryParams);
|
||||
|
||||
return clients != null && !clients.isEmpty() ? clients.get(0) : null;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 记录客户端认证信息 - 已在authenticateClient方法中内联实现
|
||||
*/
|
||||
private void recordClientAuth(String username, String authKey, String clientId, Map<String, Object> clientInfo, String accessToken) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全解析Double值
|
||||
*/
|
||||
private Double parseDouble(Object value, Double defaultValue) {
|
||||
if (value == null) return defaultValue;
|
||||
try {
|
||||
return Double.valueOf(value.toString());
|
||||
} catch (Exception e) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录客户端错误
|
||||
@@ -446,99 +226,55 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
@Override
|
||||
public void recordErrorReport(Map<String, Object> errorData) {
|
||||
ClientErrorReport errorReport = new ClientErrorReport();
|
||||
|
||||
// 基础错误信息
|
||||
errorReport.setClientId((String) errorData.get("clientId"));
|
||||
errorReport.setErrorType((String) errorData.get("errorType"));
|
||||
errorReport.setErrorMessage((String) errorData.get("errorMessage"));
|
||||
errorReport.setStackTrace((String) errorData.get("stackTrace"));
|
||||
errorReport.setErrorTime(DateUtils.getNowDate());
|
||||
|
||||
// 补充系统信息和用户名(从客户端传入的数据中获取)
|
||||
errorReport.setUsername((String) errorData.get("username"));
|
||||
errorReport.setOsName((String) errorData.get("osName"));
|
||||
errorReport.setOsVersion((String) errorData.get("osVersion"));
|
||||
errorReport.setAppVersion((String) errorData.get("appVersion"));
|
||||
|
||||
clientMonitorMapper.insertClientError(errorReport);
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录客户端数据采集报告 - 优化版:相同条件下累加数量
|
||||
* 记录客户端数据采集报告
|
||||
*/
|
||||
@Override
|
||||
public void recordDataReport(Map<String, Object> dataReport) {
|
||||
try {
|
||||
String clientId = (String) dataReport.get("clientId");
|
||||
String dataType = normalizeDataType((String) dataReport.get("dataType"));
|
||||
if (dataType == null) {
|
||||
return; // 直接跳过不记录
|
||||
}
|
||||
String status = (String) dataReport.get("status");
|
||||
int dataCount = parseInteger(dataReport.get("dataCount"), 1);
|
||||
|
||||
// 查找当天相同clientId、dataType、status的记录
|
||||
ClientDataReport existingReport = findRecentDataReport(clientId, dataType, status);
|
||||
ClientDataReport existingReport = clientMonitorMapper.findRecentDataReport(clientId, dataType, status);
|
||||
|
||||
if (existingReport != null) {
|
||||
// 累加数量到现有记录
|
||||
int newCount = existingReport.getDataCount() + dataCount;
|
||||
updateDataReportCount(existingReport.getId(), newCount);
|
||||
clientMonitorMapper.updateDataReportCount(existingReport.getId(), existingReport.getDataCount() + dataCount);
|
||||
} else {
|
||||
// 创建新记录
|
||||
ClientDataReport report = new ClientDataReport();
|
||||
report.setClientId(clientId);
|
||||
report.setDataType(dataType);
|
||||
report.setDataCount(dataCount);
|
||||
report.setCollectTime(DateUtils.getNowDate());
|
||||
report.setStatus(status);
|
||||
|
||||
// 保存到数据库
|
||||
clientMonitorMapper.insertDataReport(report);
|
||||
}
|
||||
|
||||
// 更新客户端在线状态
|
||||
if (clientId != null && !clientId.isEmpty()) {
|
||||
clientMonitorMapper.updateClientOnlineStatus(clientId, "1");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("记录数据采集失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找当天相同条件的数据报告
|
||||
*/
|
||||
private ClientDataReport findRecentDataReport(String clientId, String dataType, String status) {
|
||||
try {
|
||||
return clientMonitorMapper.findRecentDataReport(clientId, dataType, status);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新数据报告的数量
|
||||
*/
|
||||
private void updateDataReportCount(Long id, int newCount) {
|
||||
try {
|
||||
clientMonitorMapper.updateDataReportCount(id, newCount);
|
||||
} catch (Exception e) {
|
||||
System.err.println("更新数据报告数量失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标准化数据类型
|
||||
*/
|
||||
private String normalizeDataType(String dataType) {
|
||||
if (dataType == null) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
dataType = dataType.toUpperCase();
|
||||
|
||||
|
||||
// 统一数据类型标识
|
||||
if ("ORDER".equals(dataType)) {
|
||||
return "BANMA";
|
||||
} else if (dataType.contains("AMAZON")) {
|
||||
@@ -546,13 +282,9 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
} else if (dataType.contains("RAKUTEN")) {
|
||||
return "RAKUTEN";
|
||||
}
|
||||
|
||||
return dataType;
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全解析Integer值
|
||||
*/
|
||||
private Integer parseInteger(Object value, Integer defaultValue) {
|
||||
if (value == null) return defaultValue;
|
||||
try {
|
||||
@@ -567,74 +299,7 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
*/
|
||||
@Override
|
||||
public Map<String, Object> getClientDetail(String clientId) {
|
||||
// 从数据库查询客户端详细信息
|
||||
Map<String, Object> detail = clientMonitorMapper.selectClientDetail(clientId);
|
||||
// 记录API调用日志
|
||||
logApiCall("getClientDetail", "客户端ID: " + clientId);
|
||||
|
||||
return detail;
|
||||
}
|
||||
|
||||
/**
|
||||
* 记录API调用日志
|
||||
*/
|
||||
private void logApiCall(String apiName, String remark) {
|
||||
ClientDataReport report = new ClientDataReport();
|
||||
report.setClientId("system");
|
||||
report.setDataType("API_CALL");
|
||||
report.setDataCount(1);
|
||||
report.setCollectTime(DateUtils.getNowDate());
|
||||
report.setStatus("0");
|
||||
report.setRemark("调用" + apiName + "接口" + (remark != null ? ", " + remark : ""));
|
||||
clientMonitorMapper.insertDataReport(report);
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步记录API调用日志,减少阻塞
|
||||
*/
|
||||
@Async
|
||||
private void logApiCallAsync(String apiName, String remark) {
|
||||
|
||||
if (apiCallCounter.incrementAndGet() % 10 == 0) {
|
||||
logExecutor.submit(() -> {
|
||||
try {
|
||||
ClientDataReport report = new ClientDataReport();
|
||||
report.setClientId("system");
|
||||
report.setDataType("API_CALL");
|
||||
report.setDataCount(10); // 表示10次调用的批量记录
|
||||
report.setCollectTime(DateUtils.getNowDate());
|
||||
report.setStatus("0");
|
||||
report.setRemark("批量调用" + apiName + "接口" + (remark != null ? ", " + remark : ""));
|
||||
clientMonitorMapper.insertDataReport(report);
|
||||
} catch (Exception e) {
|
||||
// 日志记录失败不影响主业务
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 优雅关闭线程池
|
||||
*/
|
||||
@PreDestroy
|
||||
public void shutdown() {
|
||||
if (logExecutor != null && !logExecutor.isShutdown()) {
|
||||
logExecutor.shutdown();
|
||||
try {
|
||||
// 等待30秒让任务完成
|
||||
if (!logExecutor.awaitTermination(30, TimeUnit.SECONDS)) {
|
||||
logExecutor.shutdownNow();
|
||||
// 再等待10秒
|
||||
if (!logExecutor.awaitTermination(10, TimeUnit.SECONDS)) {
|
||||
System.err.println("线程池未能在指定时间内关闭");
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
logExecutor.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
return clientMonitorMapper.selectClientDetail(clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -642,62 +307,8 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
*/
|
||||
@Override
|
||||
public List<Map<String, Object>> getVersionDistribution() {
|
||||
// 从数据库查询真实的版本分布数据
|
||||
List<Map<String, Object>> distribution = clientMonitorMapper.selectVersionDistribution();
|
||||
|
||||
// 如果没有数据,返回空列表
|
||||
if (distribution == null) {
|
||||
distribution = new ArrayList<>();
|
||||
}
|
||||
|
||||
// 记录API调用日志
|
||||
logApiCall("getVersionDistribution", null);
|
||||
|
||||
return distribution;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 生成会话令牌
|
||||
*/
|
||||
private String generateAccessToken() {
|
||||
return UUID.randomUUID().toString().replace("-", "");
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增客户端错误报告
|
||||
*/
|
||||
@Override
|
||||
public int insertClientError(ClientErrorReport clientErrorReport) {
|
||||
return clientMonitorMapper.insertClientError(clientErrorReport);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增客户端信息
|
||||
*/
|
||||
@Override
|
||||
public int insertClientDevice(ClientDevice clientDevice) {
|
||||
return clientDeviceMapper.insert(clientDevice);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增客户端事件日志
|
||||
*/
|
||||
@Override
|
||||
public int insertClientEventLog(ClientEventLog clientEventLog) {
|
||||
return clientMonitorMapper.insertClientEventLog(clientEventLog);
|
||||
}
|
||||
|
||||
/**
|
||||
* 新增客户端数据采集报告
|
||||
*/
|
||||
@Override
|
||||
public int insertDataReport(ClientDataReport clientDataReport) {
|
||||
return clientMonitorMapper.insertDataReport(clientDataReport);
|
||||
return distribution != null ? distribution : new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -714,20 +325,11 @@ public class ClientMonitorServiceImpl implements IClientMonitorService {
|
||||
@Override
|
||||
public void cleanExpiredData() {
|
||||
try {
|
||||
// // 清理过期的客户端(设置为离线状态)
|
||||
// clientMonitorMapper.updateExpiredClientsOffline();
|
||||
|
||||
// 清理过期的设备(设置为离线状态)
|
||||
clientMonitorMapper.updateExpiredDevicesOffline();
|
||||
|
||||
// 删除过期的错误报告
|
||||
clientMonitorMapper.deleteExpiredErrorReports();
|
||||
|
||||
// 删除过期的事件日志
|
||||
clientMonitorMapper.deleteExpiredEventLogs();
|
||||
} catch (Exception e) {
|
||||
logger.error("清理过期数据失败: {}", e.getMessage(), e);
|
||||
throw new RuntimeException("清理过期数据失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,9 +50,7 @@ public class SseHubService {
|
||||
public void sendEvent(String username, String clientId, String type, String message) {
|
||||
String key = buildSessionKey(username, clientId);
|
||||
SseEmitter emitter = sessionEmitters.get(key);
|
||||
|
||||
if (emitter == null) return;
|
||||
|
||||
try {
|
||||
String data = message != null ? message : "{}";
|
||||
String eventData = "{\"type\":\"" + type + "\",\"message\":" + escapeJson(data) + "}";
|
||||
@@ -66,12 +64,28 @@ public class SseHubService {
|
||||
public void sendPing(String username, String clientId) {
|
||||
String key = buildSessionKey(username, clientId);
|
||||
SseEmitter emitter = sessionEmitters.get(key);
|
||||
if (emitter == null) return;
|
||||
if (emitter == null) {
|
||||
try {
|
||||
ClientDevice device = clientDeviceMapper.selectByDeviceId(clientId);
|
||||
// 只有当设备状态不是removed时,才更新为offline
|
||||
if (device != null && !"removed".equals(device.getStatus())) {
|
||||
device.setStatus("offline");
|
||||
device.setLastActiveAt(new Date());
|
||||
clientDeviceMapper.updateByDeviceId(device);
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
// 静默处理,不影响心跳主流程
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
emitter.send(SseEmitter.event().name("ping").data(String.valueOf(System.currentTimeMillis())));
|
||||
} catch (IOException e) {
|
||||
sessionEmitters.remove(key);
|
||||
try { emitter.complete(); } catch (Exception ignored) {}
|
||||
// 发送失败也更新为离线
|
||||
updateDeviceStatus(clientId, "offline");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,6 +135,10 @@ public class SseHubService {
|
||||
try {
|
||||
ClientDevice device = clientDeviceMapper.selectByDeviceId(deviceId);
|
||||
if (device != null) {
|
||||
if ("removed".equals(device.getStatus()) && "offline".equals(status)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ("removed".equals(status)) {
|
||||
disconnectDevice(device.getUsername(), deviceId);
|
||||
}
|
||||
|
||||
@@ -33,12 +33,4 @@ public class DeviceHeartbeatTask {
|
||||
sseHubService.sendPing(device.getUsername(), device.getDeviceId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 每2分钟清理一次过期设备
|
||||
*/
|
||||
@Scheduled(fixedRate = 120000)
|
||||
public void cleanExpiredDevices() {
|
||||
clientDeviceMapper.updateExpiredDevicesOffline();
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,7 @@ spring:
|
||||
druid:
|
||||
# 主库数据源
|
||||
master:
|
||||
url: jdbc:mysql://8.138.23.49:8896/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
||||
url: jdbc:mysql://8.138.23.49:8896/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&autoReconnect=true&failOverReadOnly=false&maxReconnects=3&initialTimeout=2&connectTimeout=5000&socketTimeout=5000
|
||||
username: root
|
||||
password: jaz7fMSiCrQK48nK
|
||||
# url: jdbc:mysql://localhost:3306/erp?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
|
||||
@@ -19,20 +19,20 @@ spring:
|
||||
url:
|
||||
username:
|
||||
password:
|
||||
# 初始连接数
|
||||
initialSize: 5
|
||||
# 初始连接数(增加预热连接)
|
||||
initialSize: 8
|
||||
# 最小连接池数量
|
||||
minIdle: 10
|
||||
# 最大连接池数量
|
||||
maxActive: 20
|
||||
# 配置获取连接等待超时的时间
|
||||
maxWait: 60000
|
||||
# 配置连接超时时间
|
||||
connectTimeout: 30000
|
||||
# 配置网络超时时间
|
||||
socketTimeout: 60000
|
||||
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
|
||||
timeBetweenEvictionRunsMillis: 60000
|
||||
maxActive: 25
|
||||
# 配置获取连接等待超时的时间(5秒)
|
||||
maxWait: 5000
|
||||
# 配置连接超时时间(5秒)
|
||||
connectTimeout: 5000
|
||||
# 配置网络超时时间(5秒)
|
||||
socketTimeout: 5000
|
||||
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒(30秒检测一次)
|
||||
timeBetweenEvictionRunsMillis: 30000
|
||||
# 配置一个连接在池中最小生存的时间,单位是毫秒
|
||||
minEvictableIdleTimeMillis: 300000
|
||||
# 配置一个连接在池中最大生存的时间,单位是毫秒
|
||||
@@ -55,9 +55,9 @@ spring:
|
||||
filter:
|
||||
stat:
|
||||
enabled: true
|
||||
# 慢SQL记录
|
||||
# 慢SQL记录(500ms以上记录为慢SQL)
|
||||
log-slow-sql: true
|
||||
slow-sql-millis: 1000
|
||||
slow-sql-millis: 500
|
||||
merge-sql: true
|
||||
wall:
|
||||
config:
|
||||
|
||||
@@ -88,7 +88,7 @@ spring:
|
||||
# password:
|
||||
password: 123123
|
||||
# 连接超时时间(降低超时,快速失败)
|
||||
timeout: 3s
|
||||
timeout: 5s
|
||||
lettuce:
|
||||
pool:
|
||||
# 连接池中的最小空闲连接(保持预热连接,避免临时建连)
|
||||
@@ -98,7 +98,7 @@ spring:
|
||||
# 连接池的最大数据库连接数(增加以应对并发)
|
||||
max-active: 20
|
||||
# 连接池最大阻塞等待时间(设置合理超时,避免无限等待)
|
||||
max-wait: 3000ms
|
||||
max-wait: 5000ms
|
||||
# 关闭超时时间
|
||||
shutdown-timeout: 100ms
|
||||
|
||||
|
||||
@@ -10,7 +10,9 @@ PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
|
||||
<!-- 允许JDBC 支持自动生成主键 -->
|
||||
<setting name="useGeneratedKeys" value="true" />
|
||||
<!-- 配置默认的执行器.SIMPLE就是普通执行器;REUSE执行器会重用预处理语句(prepared statements);BATCH执行器将重用语句并执行批量更新 -->
|
||||
<setting name="defaultExecutorType" value="SIMPLE" />
|
||||
<setting name="defaultExecutorType" value="REUSE" />
|
||||
<!-- 设置超时时间,防止慢查询(5秒) -->
|
||||
<setting name="defaultStatementTimeout" value="5" />
|
||||
<!-- 指定 MyBatis 所用日志的具体实现 -->
|
||||
<setting name="logImpl" value="SLF4J" />
|
||||
<!-- 使用驼峰命名法转换字段 -->
|
||||
|
||||
Reference in New Issue
Block a user