refactor: 重构目录结构统一规范
- shared/ → common/(constant、enums、model) - framework/cache/config/ → framework/cache/(扁平化) - framework/integration/captcha/ → framework/captcha/ - config/property/ → 各模块 config/ 下 - interfaces/ → module/(sse、mail、sms) - 移除冗余枚举 LogModuleEnum
This commit is contained in:
1 parent
234b12f297
commit
9cd3ff88f8
78 files changed
+161
-275
No files matched your search
@@ -0,0 +1,96 @@
|
||||
package com.youlai.boot.module.codegen.config;
|
||||
|
||||
import cn.hutool.core.io.file.FileNameUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 代码生成配置属性
|
||||
*
|
||||
* @author Ray
|
||||
* @since 2.11.0
|
||||
*/
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "codegen")
|
||||
@Data
|
||||
public class CodegenProperties {
|
||||
|
||||
|
||||
/**
|
||||
* 默认配置
|
||||
*/
|
||||
private DefaultConfig defaultConfig ;
|
||||
|
||||
/**
|
||||
* 模板配置
|
||||
*/
|
||||
private Map<String, TemplateConfig> templateConfigs = MapUtil.newHashMap(true);
|
||||
|
||||
/**
|
||||
* 后端应用名
|
||||
*/
|
||||
private String backendAppName;
|
||||
|
||||
/**
|
||||
* 前端应用名
|
||||
*/
|
||||
private String frontendAppName;
|
||||
|
||||
/**
|
||||
* 下载文件名
|
||||
*/
|
||||
private String downloadFileName;
|
||||
|
||||
/**
|
||||
* 排除数据表
|
||||
*/
|
||||
private List<String> excludeTables;
|
||||
|
||||
/**
|
||||
* 模板配置
|
||||
*/
|
||||
@Data
|
||||
public static class TemplateConfig {
|
||||
|
||||
/**
|
||||
* 模板路径 (e.g. /templates/codegen/controller.java.vm)
|
||||
*/
|
||||
private String templatePath;
|
||||
|
||||
/**
|
||||
* 子包名 (e.g. controller/service/mapper/model)
|
||||
*/
|
||||
private String subpackageName;
|
||||
|
||||
/**
|
||||
* 文件扩展名,如 .java
|
||||
*/
|
||||
private String extension = FileNameUtil.EXT_JAVA;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 默认配置
|
||||
*/
|
||||
@Data
|
||||
public static class DefaultConfig {
|
||||
|
||||
/**
|
||||
* 作者 (e.g. Ray)
|
||||
*/
|
||||
private String author;
|
||||
|
||||
/**
|
||||
* 默认模块名(e.g. system)
|
||||
*/
|
||||
private String moduleName;
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -3,7 +3,7 @@ package com.youlai.boot.module.codegen.controller;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.common.result.PageResult;
|
||||
import com.youlai.boot.common.result.Result;
|
||||
import com.youlai.boot.config.property.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.config.CodegenProperties;
|
||||
import com.youlai.boot.common.enums.ActionTypeEnum;
|
||||
import com.youlai.boot.common.enums.LogModuleEnum;
|
||||
import com.youlai.boot.module.codegen.service.CodegenService;
|
||||
|
||||
@@ -2,8 +2,8 @@ package com.youlai.boot.module.codegen.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.module.codegen.model.bo.ColumnMetaData;
|
||||
import com.youlai.boot.module.codegen.model.bo.TableMetaData;
|
||||
import com.youlai.boot.module.codegen.model.vo.ColumnMetaVO;
|
||||
import com.youlai.boot.module.codegen.model.vo.TableMetaVO;
|
||||
import com.youlai.boot.module.codegen.model.query.TableQuery;
|
||||
import com.youlai.boot.module.codegen.model.vo.TablePageVO;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
@@ -35,13 +35,7 @@ public interface DatabaseMapper extends BaseMapper {
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
List<ColumnMetaData> getTableColumns(String tableName);
|
||||
List<ColumnMetaVO> getTableColumns(String tableName);
|
||||
|
||||
/**
|
||||
* 获取表元数据
|
||||
*
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
TableMetaData getTableMetadata(String tableName);
|
||||
TableMetaVO getTableMetadata(String tableName);
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package com.youlai.boot.module.codegen.model.bo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "数据表字段Vo")
|
||||
@Data
|
||||
public class ColumnMetaData {
|
||||
|
||||
/**
|
||||
* 字段名称
|
||||
*/
|
||||
private String columnName;
|
||||
|
||||
/**
|
||||
* 字段类型
|
||||
*/
|
||||
private String dataType;
|
||||
|
||||
/**
|
||||
* 字段描述
|
||||
*/
|
||||
private String columnComment;
|
||||
|
||||
/**
|
||||
* 字段长度
|
||||
*/
|
||||
private Long characterMaximumLength;
|
||||
|
||||
/**
|
||||
* 是否主键(1-是 0-否)
|
||||
*/
|
||||
private Integer isPrimaryKey;
|
||||
|
||||
/**
|
||||
* 是否可为空(1-是 0-否)
|
||||
*/
|
||||
private String isNullable;
|
||||
|
||||
/**
|
||||
* 字符集
|
||||
*/
|
||||
private String characterSetName;
|
||||
|
||||
/**
|
||||
* 排序规则
|
||||
*/
|
||||
private String collationName;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.youlai.boot.module.codegen.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "数据表字段元数据")
|
||||
@Data
|
||||
public class ColumnMetaVO {
|
||||
|
||||
private String columnName;
|
||||
|
||||
private String dataType;
|
||||
|
||||
private String columnComment;
|
||||
|
||||
private Long characterMaximumLength;
|
||||
|
||||
private Integer isPrimaryKey;
|
||||
|
||||
private String isNullable;
|
||||
|
||||
private String characterSetName;
|
||||
|
||||
private String collationName;
|
||||
|
||||
}
|
||||
+2
-21
@@ -1,8 +1,7 @@
|
||||
package com.youlai.boot.module.codegen.model.bo;
|
||||
package com.youlai.boot.module.codegen.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
|
||||
/**
|
||||
* 数据表元数据
|
||||
*
|
||||
@@ -10,36 +9,18 @@ import lombok.Data;
|
||||
* @since 2.10.0
|
||||
*/
|
||||
@Data
|
||||
public class TableMetaData {
|
||||
public class TableMetaVO {
|
||||
|
||||
/**
|
||||
* 表名称
|
||||
*/
|
||||
private String tableName;
|
||||
|
||||
/**
|
||||
* 表描述
|
||||
*/
|
||||
private String tableComment;
|
||||
|
||||
/**
|
||||
* 排序规则
|
||||
*/
|
||||
private String tableCollation;
|
||||
|
||||
/**
|
||||
* 存储引擎
|
||||
*/
|
||||
private String engine;
|
||||
|
||||
/**
|
||||
* 字符集
|
||||
*/
|
||||
private String charset;
|
||||
|
||||
/**
|
||||
* 创建时间
|
||||
*/
|
||||
private String createTime;
|
||||
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import cn.hutool.extra.template.TemplateUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.youlai.boot.module.codegen.enums.JavaTypeEnum;
|
||||
import com.youlai.boot.config.property.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.config.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.service.GenTableService;
|
||||
import com.youlai.boot.module.codegen.service.GenTableColumnService;
|
||||
import com.youlai.boot.module.codegen.service.CodegenService;
|
||||
|
||||
+14
-14
@@ -11,12 +11,12 @@ import com.youlai.boot.module.codegen.enums.FormTypeEnum;
|
||||
import com.youlai.boot.module.codegen.enums.JavaTypeEnum;
|
||||
import com.youlai.boot.module.codegen.enums.QueryTypeEnum;
|
||||
import com.youlai.boot.common.exception.BusinessException;
|
||||
import com.youlai.boot.config.property.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.config.CodegenProperties;
|
||||
import com.youlai.boot.module.codegen.converter.CodegenConverter;
|
||||
import com.youlai.boot.module.codegen.mapper.DatabaseMapper;
|
||||
import com.youlai.boot.module.codegen.mapper.GenTableMapper;
|
||||
import com.youlai.boot.module.codegen.model.bo.ColumnMetaData;
|
||||
import com.youlai.boot.module.codegen.model.bo.TableMetaData;
|
||||
import com.youlai.boot.module.codegen.model.vo.ColumnMetaVO;
|
||||
import com.youlai.boot.module.codegen.model.vo.TableMetaVO;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTable;
|
||||
import com.youlai.boot.module.codegen.model.entity.GenTableColumn;
|
||||
import com.youlai.boot.module.codegen.model.form.GenConfigForm;
|
||||
@@ -72,7 +72,7 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
|
||||
|
||||
// 如果没有代码生成配置,则根据表的元数据生成默认配置
|
||||
if (genTable == null) {
|
||||
TableMetaData tableMetadata = databaseMapper.getTableMetadata(tableName);
|
||||
TableMetaVO tableMetadata = databaseMapper.getTableMetadata(tableName);
|
||||
Assert.isTrue(tableMetadata != null, "未找到表元数据");
|
||||
|
||||
genTable = new GenTable();
|
||||
@@ -100,7 +100,7 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
|
||||
List<GenTableColumn> genTableColumns = new ArrayList<>();
|
||||
|
||||
// 获取表的列
|
||||
List<ColumnMetaData> tableColumns = databaseMapper.getTableColumns(tableName);
|
||||
List<ColumnMetaVO> tableColumns = databaseMapper.getTableColumns(tableName);
|
||||
if (CollectionUtil.isNotEmpty(tableColumns)) {
|
||||
// 查询字段生成配置
|
||||
List<GenTableColumn> fieldConfigList = genTableColumnService.list(
|
||||
@@ -113,7 +113,7 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
|
||||
.filter(Objects::nonNull) // 过滤掉空值
|
||||
.max(Integer::compareTo)
|
||||
.orElse(0);
|
||||
for (ColumnMetaData tableColumn : tableColumns) {
|
||||
for (ColumnMetaVO tableColumn : tableColumns) {
|
||||
// 根据列名获取字段生成配置
|
||||
String columnName = tableColumn.getColumnName();
|
||||
GenTableColumn fieldConfig = fieldConfigList.stream()
|
||||
@@ -150,16 +150,16 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
|
||||
/**
|
||||
* 创建默认字段配置
|
||||
*
|
||||
* @param columnMetaData 表字段元数据
|
||||
* @param columnMetaVO 表字段元数据
|
||||
* @return
|
||||
*/
|
||||
private GenTableColumn createDefaultFieldConfig(ColumnMetaData columnMetaData) {
|
||||
private GenTableColumn createDefaultFieldConfig(ColumnMetaVO columnMetaVO) {
|
||||
GenTableColumn fieldConfig = new GenTableColumn();
|
||||
fieldConfig.setColumnName(columnMetaData.getColumnName());
|
||||
fieldConfig.setColumnType(columnMetaData.getDataType());
|
||||
fieldConfig.setFieldComment(columnMetaData.getColumnComment());
|
||||
fieldConfig.setFieldName(StrUtil.toCamelCase(columnMetaData.getColumnName()));
|
||||
fieldConfig.setIsRequired("YES".equals(columnMetaData.getIsNullable()) ? 0 : 1);
|
||||
fieldConfig.setColumnName(columnMetaVO.getColumnName());
|
||||
fieldConfig.setColumnType(columnMetaVO.getDataType());
|
||||
fieldConfig.setFieldComment(columnMetaVO.getColumnComment());
|
||||
fieldConfig.setFieldName(StrUtil.toCamelCase(columnMetaVO.getColumnName()));
|
||||
fieldConfig.setIsRequired("YES".equals(columnMetaVO.getIsNullable()) ? 0 : 1);
|
||||
|
||||
String columnType = StrUtil.blankToDefault(fieldConfig.getColumnType(), "").toLowerCase();
|
||||
if ("date".equals(columnType)) {
|
||||
@@ -171,7 +171,7 @@ public class GenTableServiceImpl extends ServiceImpl<GenTableMapper, GenTable> i
|
||||
}
|
||||
|
||||
fieldConfig.setQueryType(QueryTypeEnum.EQ);
|
||||
fieldConfig.setMaxLength(columnMetaData.getCharacterMaximumLength());
|
||||
fieldConfig.setMaxLength(columnMetaVO.getCharacterMaximumLength());
|
||||
return fieldConfig;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.youlai.boot.module.sse.controller;
|
||||
|
||||
import com.youlai.boot.common.result.Result;
|
||||
import com.youlai.boot.framework.security.model.SysUserDetails;
|
||||
import com.youlai.boot.framework.security.util.SecurityUtils;
|
||||
import com.youlai.boot.module.sse.service.SseService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
/**
|
||||
* SSE 控制器
|
||||
*/
|
||||
@Tag(name = "14. SSE连接")
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/sse")
|
||||
@RequiredArgsConstructor
|
||||
public class SseController {
|
||||
|
||||
private final SseService sseService;
|
||||
|
||||
@Operation(summary = "建立SSE连接")
|
||||
@GetMapping(value = "/connect", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
|
||||
public SseEmitter connect() {
|
||||
SysUserDetails user = SecurityUtils.getUser().orElse(null);
|
||||
if (user == null) {
|
||||
log.warn("SSE连接失败:未获取到当前用户");
|
||||
return null;
|
||||
}
|
||||
return sseService.createConnection(user.getUsername());
|
||||
}
|
||||
|
||||
@Operation(summary = "获取在线用户数")
|
||||
@GetMapping("/online-count")
|
||||
public Result<Integer> getOnlineCount() {
|
||||
return Result.success(sseService.getOnlineUserCount());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.youlai.boot.module.sse.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 字典变更事件
|
||||
* <p>
|
||||
* 当字典数据发生变更时,通过 SSE 广播此事件通知前端清除缓存。
|
||||
* 前端收到通知后清除对应字典的本地缓存,下次使用时重新从服务端加载。
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class DictChangeEvent implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 字典编码 */
|
||||
private String dictCode;
|
||||
|
||||
/** 事件时间戳 */
|
||||
private long timestamp;
|
||||
|
||||
/**
|
||||
* 创建字典变更事件(自动设置当前时间戳)
|
||||
*
|
||||
* @param dictCode 字典编码
|
||||
*/
|
||||
public DictChangeEvent(String dictCode) {
|
||||
this.dictCode = dictCode;
|
||||
this.timestamp = System.currentTimeMillis();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.youlai.boot.module.sse.dto;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serial;
|
||||
import java.io.Serializable;
|
||||
|
||||
/**
|
||||
* 在线用户信息DTO
|
||||
* <p>
|
||||
* 用于返回在线用户的基本信息,包括用户名、会话数量和登录时间。
|
||||
*
|
||||
* @author Ray.Hao
|
||||
* @since 3.0.0
|
||||
*/
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class OnlineUserDTO implements Serializable {
|
||||
|
||||
@Serial
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/** 用户名 */
|
||||
private String username;
|
||||
|
||||
/** 会话数量(多设备登录时大于1) */
|
||||
private int sessionCount;
|
||||
|
||||
/** 最早登录时间 */
|
||||
private long loginTime;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.youlai.boot.module.sse.job;
|
||||
|
||||
import com.youlai.boot.module.sse.registry.SseSessionRegistry;
|
||||
import com.youlai.boot.module.sse.service.SseService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 在线用户数统计定时任务
|
||||
* <p>
|
||||
* 定时统计并广播当前在线用户数量到所有 SSE 客户端
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class OnlineUserCountJob {
|
||||
|
||||
private final SseSessionRegistry sessionRegistry;
|
||||
private final SseService sseService;
|
||||
|
||||
/**
|
||||
* 定时统计在线用户数并广播
|
||||
* <p>
|
||||
* 每3分钟执行一次,推送当前在线用户数量
|
||||
*/
|
||||
@Scheduled(cron = "0 */3 * * * ?")
|
||||
public void execute() {
|
||||
int onlineCount = sessionRegistry.getOnlineUserCount();
|
||||
int connectionCount = sessionRegistry.getTotalConnectionCount();
|
||||
|
||||
log.debug("定时统计:在线用户数={}, 总连接数={}", onlineCount, connectionCount);
|
||||
|
||||
// 发送在线用户数量
|
||||
sseService.sendOnlineCount();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package com.youlai.boot.module.sse.registry;
|
||||
|
||||
import com.youlai.boot.module.sse.dto.OnlineUserDTO;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* SSE 会话注册表
|
||||
* <p>
|
||||
* 维护 SSE 连接的用户会话信息,支持多设备同时登录
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class SseSessionRegistry {
|
||||
|
||||
/** 用户名 -> SseEmitter 集合(支持多设备) */
|
||||
private final Map<String, Set<SseEmitter>> userEmittersMap = new ConcurrentHashMap<>();
|
||||
|
||||
/** SseEmitter -> 用户名(快速定位用户) */
|
||||
private final Map<SseEmitter, String> emitterUserMap = new ConcurrentHashMap<>();
|
||||
|
||||
/** SseEmitter -> 连接时间 */
|
||||
private final Map<SseEmitter, Long> emitterTimeMap = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 用户上线(建立 SSE 连接)
|
||||
*
|
||||
* @param username 用户名
|
||||
* @param emitter SseEmitter
|
||||
*/
|
||||
public void userConnected(String username, SseEmitter emitter) {
|
||||
userEmittersMap.computeIfAbsent(username, k -> ConcurrentHashMap.newKeySet()).add(emitter);
|
||||
emitterUserMap.put(emitter, username);
|
||||
emitterTimeMap.put(emitter, System.currentTimeMillis());
|
||||
log.debug("用户[{}]SSE连接已建立", username);
|
||||
|
||||
// 设置连接超时和完成回调
|
||||
emitter.onCompletion(() -> {
|
||||
removeEmitter(emitter);
|
||||
log.debug("用户[{}]SSE连接已完成", username);
|
||||
});
|
||||
emitter.onTimeout(() -> {
|
||||
removeEmitter(emitter);
|
||||
log.debug("用户[{}]SSE连接超时", username);
|
||||
});
|
||||
emitter.onError(e -> {
|
||||
removeEmitter(emitter);
|
||||
log.debug("用户[{}]SSE连接错误: {}", username, e.getMessage());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 移除指定 emitter
|
||||
*/
|
||||
private void removeEmitter(SseEmitter emitter) {
|
||||
String username = emitterUserMap.remove(emitter);
|
||||
if (username == null) {
|
||||
return;
|
||||
}
|
||||
emitterTimeMap.remove(emitter);
|
||||
|
||||
Set<SseEmitter> emitters = userEmittersMap.get(username);
|
||||
if (emitters != null) {
|
||||
emitters.remove(emitter);
|
||||
if (emitters.isEmpty()) {
|
||||
userEmittersMap.remove(username);
|
||||
log.debug("用户[{}]所有SSE连接已断开", username);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户下线(断开所有 SSE 连接)
|
||||
*
|
||||
* @param username 用户名
|
||||
*/
|
||||
public void userDisconnected(String username) {
|
||||
Set<SseEmitter> emitters = userEmittersMap.remove(username);
|
||||
if (emitters == null) {
|
||||
return;
|
||||
}
|
||||
emitters.forEach(emitter -> {
|
||||
emitterUserMap.remove(emitter);
|
||||
emitterTimeMap.remove(emitter);
|
||||
try {
|
||||
emitter.complete();
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
});
|
||||
log.debug("用户[{}]已下线,移除{}个SSE连接", username, emitters.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取在线用户数量
|
||||
*/
|
||||
public int getOnlineUserCount() {
|
||||
return userEmittersMap.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取总连接数量(包括多设备)
|
||||
*/
|
||||
public int getTotalConnectionCount() {
|
||||
return emitterUserMap.size();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定用户的连接数量
|
||||
*/
|
||||
public int getUserConnectionCount(String username) {
|
||||
Set<SseEmitter> emitters = userEmittersMap.get(username);
|
||||
return emitters != null ? emitters.size() : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户是否在线
|
||||
*/
|
||||
public boolean isUserOnline(String username) {
|
||||
Set<SseEmitter> emitters = userEmittersMap.get(username);
|
||||
return emitters != null && !emitters.isEmpty();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有在线用户列表
|
||||
*/
|
||||
public List<OnlineUserDTO> getOnlineUsers() {
|
||||
return userEmittersMap.entrySet().stream()
|
||||
.map(entry -> {
|
||||
String username = entry.getKey();
|
||||
Set<SseEmitter> emitters = entry.getValue();
|
||||
long earliestTime = emitters.stream()
|
||||
.map(emitterTimeMap::get)
|
||||
.filter(t -> t != null)
|
||||
.mapToLong(Long::longValue)
|
||||
.min()
|
||||
.orElse(System.currentTimeMillis());
|
||||
return new OnlineUserDTO(username, emitters.size(), earliestTime);
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有活跃的 SseEmitter
|
||||
*/
|
||||
public Set<SseEmitter> getAllEmitters() {
|
||||
return emitterUserMap.keySet();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定用户的所有 SseEmitter
|
||||
*/
|
||||
public Set<SseEmitter> getUserEmitters(String username) {
|
||||
return userEmittersMap.get(username);
|
||||
}
|
||||
|
||||
/**
|
||||
* 向指定 emitter 发送事件
|
||||
*/
|
||||
public boolean sendEvent(SseEmitter emitter, String eventName, Object data) {
|
||||
try {
|
||||
emitter.send(SseEmitter.event()
|
||||
.name(eventName)
|
||||
.data(data));
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
log.warn("发送SSE事件失败: {}", e.getMessage());
|
||||
removeEmitter(emitter);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 向所有连接广播事件
|
||||
*/
|
||||
public void broadcast(String eventName, Object data) {
|
||||
getAllEmitters().forEach(emitter -> sendEvent(emitter, eventName, data));
|
||||
}
|
||||
|
||||
/**
|
||||
* 向指定用户发送事件
|
||||
*/
|
||||
public void sendToUser(String username, String eventName, Object data) {
|
||||
Set<SseEmitter> emitters = userEmittersMap.get(username);
|
||||
if (emitters != null) {
|
||||
emitters.forEach(emitter -> sendEvent(emitter, eventName, data));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.youlai.boot.module.sse.service;
|
||||
|
||||
import com.youlai.boot.module.sse.dto.DictChangeEvent;
|
||||
import com.youlai.boot.module.sse.dto.OnlineUserDTO;
|
||||
import com.youlai.boot.module.sse.registry.SseSessionRegistry;
|
||||
import com.youlai.boot.module.sse.topic.SseTopics;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* SSE 服务
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SseService {
|
||||
|
||||
/** SSE 连接超时时间:30 分钟 */
|
||||
private static final long TIMEOUT = 30 * 60 * 1000L;
|
||||
|
||||
private final SseSessionRegistry sessionRegistry;
|
||||
|
||||
/**
|
||||
* 创建 SSE 连接
|
||||
*
|
||||
* @param username 用户名
|
||||
* @return SseEmitter
|
||||
*/
|
||||
public SseEmitter createConnection(String username) {
|
||||
if (username == null || username.isEmpty()) {
|
||||
log.warn("创建SSE连接失败:用户名为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 创建 SseEmitter,设置超时时间
|
||||
SseEmitter emitter = new SseEmitter(TIMEOUT);
|
||||
|
||||
// 注册用户连接
|
||||
sessionRegistry.userConnected(username, emitter);
|
||||
|
||||
// 连接建立后立即发送在线用户数
|
||||
try {
|
||||
emitter.send(SseEmitter.event()
|
||||
.name(SseTopics.ONLINE_COUNT)
|
||||
.data(sessionRegistry.getOnlineUserCount()));
|
||||
} catch (IOException e) {
|
||||
log.warn("发送初始在线用户数失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
log.info("用户[{}]SSE连接已建立,当前在线用户数: {}", username, sessionRegistry.getOnlineUserCount());
|
||||
|
||||
// 发送在线用户数变更
|
||||
sendOnlineCount();
|
||||
|
||||
return emitter;
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送字典变更事件
|
||||
*
|
||||
* @param dictCode 字典编码
|
||||
*/
|
||||
public void sendDictChange(String dictCode) {
|
||||
if (dictCode == null || dictCode.isEmpty()) {
|
||||
log.warn("字典编码为空,跳过发送");
|
||||
return;
|
||||
}
|
||||
|
||||
DictChangeEvent event = new DictChangeEvent(dictCode);
|
||||
sessionRegistry.broadcast(SseTopics.DICT, event);
|
||||
log.info("已发送字典变更通知: dictCode={}", dictCode);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送在线用户数
|
||||
*/
|
||||
public void sendOnlineCount() {
|
||||
int count = sessionRegistry.getOnlineUserCount();
|
||||
sessionRegistry.broadcast(SseTopics.ONLINE_COUNT, count);
|
||||
log.debug("已发送在线用户数: {}", count);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送消息给指定用户
|
||||
*
|
||||
* @param username 用户名
|
||||
* @param eventName 事件名称
|
||||
* @param data 数据
|
||||
*/
|
||||
public void sendToUser(String username, String eventName, Object data) {
|
||||
if (username == null || username.isEmpty()) {
|
||||
log.warn("用户名为空,无法发送消息");
|
||||
return;
|
||||
}
|
||||
sessionRegistry.sendToUser(username, eventName, data);
|
||||
log.info("已向用户[{}]发送事件[{}]", username, eventName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取在线用户列表
|
||||
*
|
||||
* @return 在线用户列表
|
||||
*/
|
||||
public List<OnlineUserDTO> getOnlineUsers() {
|
||||
return sessionRegistry.getOnlineUsers();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取在线用户数
|
||||
*
|
||||
* @return 在线用户数
|
||||
*/
|
||||
public int getOnlineUserCount() {
|
||||
return sessionRegistry.getOnlineUserCount();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送系统消息
|
||||
*
|
||||
* @param message 消息内容
|
||||
*/
|
||||
public void sendSystemMessage(String message) {
|
||||
if (message == null || message.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Map<String, Object> systemMessage = Map.of(
|
||||
"sender", "系统通知",
|
||||
"content", message,
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
sessionRegistry.broadcast(SseTopics.SYSTEM, systemMessage);
|
||||
log.info("已发送系统消息: {}", message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.youlai.boot.module.sse.topic;
|
||||
|
||||
/**
|
||||
* SSE 主题常量
|
||||
*/
|
||||
public final class SseTopics {
|
||||
|
||||
private SseTopics() {
|
||||
}
|
||||
|
||||
/** 字典变更事件 */
|
||||
public static final String DICT = "dict";
|
||||
|
||||
/** 在线用户数事件 */
|
||||
public static final String ONLINE_COUNT = "online-count";
|
||||
|
||||
/** 系统消息事件 */
|
||||
public static final String SYSTEM = "system";
|
||||
}
|
||||
Reference in new issue
Block a user