创建雪花算法类kb-foundation/src/main/java/com/knowledge/base/common/utils/SnowflakeIdGenerator.java:
package com.knowledge.base.common.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
/**
* 雪花算法ID生成器
*
* <p>采用Twitter Snowflake算法实现分布式ID生成,保证全局唯一性</p>
* <p>生成19位数字的Long类型ID</p>
*
* <p>ID结构:1位符号位 + 41位时间戳 + 10位机器ID + 12位序列号</p>
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@Component
public class SnowflakeIdGenerator {
private static final long START_TIMESTAMP = 1704067200000L;
private static final long DATACENTER_ID_BITS = 5L;
private static final long WORKER_ID_BITS = 5L;
private static final long SEQUENCE_BITS = 12L;
private static final long MAX_DATACENTER_ID = ~(-1L << DATACENTER_ID_BITS);
private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);
private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
private static final long DATACENTER_ID_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;
private static final long TIMESTAMP_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS + DATACENTER_ID_BITS;
private final long datacenterId;
private final long workerId;
private long sequence = 0L;
private long lastTimestamp = -1L;
private static volatile SnowflakeIdGenerator instance;
@jakarta.annotation.PostConstruct
public void init() {
log.info("SnowflakeIdGenerator initialized with datacenterId: {}, workerId: {}", datacenterId, workerId);
}
public SnowflakeIdGenerator() {
this(1L, 1L);
}
public SnowflakeIdGenerator(long datacenterId, long workerId) {
if (datacenterId > MAX_DATACENTER_ID || datacenterId < 0) {
throw new IllegalArgumentException(
String.format("Datacenter ID can't be greater than %d or less than 0", MAX_DATACENTER_ID));
}
if (workerId > MAX_WORKER_ID || workerId < 0) {
throw new IllegalArgumentException(
String.format("Worker ID can't be greater than %d or less than 0", MAX_WORKER_ID));
}
this.datacenterId = datacenterId;
this.workerId = workerId;
}
public static SnowflakeIdGenerator getInstance(long datacenterId, long workerId) {
if (instance == null) {
synchronized (SnowflakeIdGenerator.class) {
if (instance == null) {
instance = new SnowflakeIdGenerator(datacenterId, workerId);
}
}
}
return instance;
}
public static SnowflakeIdGenerator getInstance() {
return getInstance(1L, 1L);
}
public synchronized long nextId() {
long timestamp = getCurrentTimestamp();
if (timestamp < lastTimestamp) {
long offset = lastTimestamp - timestamp;
if (offset <= 5) {
try {
Thread.sleep(offset << 1);
timestamp = getCurrentTimestamp();
if (timestamp < lastTimestamp) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
} catch (InterruptedException e) {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
} else {
throw new RuntimeException("Clock moved backwards. Refusing to generate id");
}
}
if (timestamp == lastTimestamp) {
sequence = (sequence + 1) & MAX_SEQUENCE;
if (sequence == 0) {
timestamp = waitNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
return ((timestamp - START_TIMESTAMP) << TIMESTAMP_SHIFT)
| (datacenterId << DATACENTER_ID_SHIFT)
| (workerId << WORKER_ID_SHIFT)
| sequence;
}
public String nextIdStr() {
return String.valueOf(nextId());
}
private long waitNextMillis(long lastTimestamp) {
long timestamp = getCurrentTimestamp();
while (timestamp <= lastTimestamp) {
timestamp = getCurrentTimestamp();
}
return timestamp;
}
private long getCurrentTimestamp() {
return System.currentTimeMillis();
}
}9.2 系统配置服务
创建接口 kb-foundation/src/main/java/com/knowledge/base/foundation/service/SystemConfigService.java:
package com.knowledge.base.foundation.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.foundation.entity.SystemConfig;
import java.util.List;
import java.util.Map;
/**
* 系统配置服务接口
*
* @author 苏三
* @since 1.0.0
*/
public interface SystemConfigService {
/**
* 分页查询配置列表
*
* @param current 当前页
* @param size 每页大小
* @param category 配置分类
* @return 配置分页信息
*/
IPage<SystemConfig> pageConfigs(Long current, Long size, String category);
/**
* 根据配置键查询配置项
*
* @param key 配置键
* @return 配置信息
*/
SystemConfig getConfigByKey(String key);
/**
* 创建配置
*
* @param config 配置信息
* @return 是否成功
*/
Boolean createConfig(SystemConfig config);
/**
* 更新配置
*
* @param key 配置键
* @param config 配置信息
* @return 是否成功
*/
Boolean updateConfig(String key, SystemConfig config);
/**
* 删除配置
*
* @param key 配置键
* @return 是否成功
*/
Boolean deleteConfig(String key);
/**
* 按分类获取配置
*
* @param category 配置分类
* @return 配置列表
*/
List<SystemConfig> getConfigsByCategory(String category);
/**
* 获取公开配置
*
* @return 公开配置Map
*/
Map<String, String> getPublicConfigs();
}创建实现类 kb-foundation/src/main/java/com/knowledge/base/foundation/service/impl/SystemConfigServiceImpl.java:
package com.knowledge.base.foundation.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.foundation.entity.SystemConfig;
import com.knowledge.base.foundation.mapper.SystemConfigMapper;
import com.knowledge.base.foundation.service.SystemConfigService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 系统配置服务实现类
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@Service
public class SystemConfigServiceImpl extends ServiceImpl<SystemConfigMapper, SystemConfig> implements SystemConfigService {
@Resource
private SystemConfigMapper systemConfigMapper;
@Override
public IPage<SystemConfig> pageConfigs(Long current, Long size, String category) {
log.info("分页查询配置:current={}, size={}, category={}", current, size, category);
LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
if (StringUtils.hasText(category)) {
wrapper.eq(SystemConfig::getCategory, category);
}
wrapper.orderByAsc(SystemConfig::getId);
Page<SystemConfig> page = new Page<>(current, size);
return systemConfigMapper.selectPage(page, wrapper);
}
@Override
@Cacheable(value = "systemConfig", key = "#key")
public SystemConfig getConfigByKey(String key) {
log.info("获取配置:key={}", key);
if (!StringUtils.hasText(key)) {
throw new BusinessException("配置键不能为空");
}
return systemConfigMapper.selectByConfigKey(key);
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = "systemConfig", allEntries = true)
public Boolean createConfig(SystemConfig config) {
log.info("创建配置:key={}", config.getConfigKey());
if (!StringUtils.hasText(config.getConfigKey())) {
throw new BusinessException("配置键不能为空");
}
SystemConfig existConfig = systemConfigMapper.selectByConfigKey(config.getConfigKey());
if (existConfig != null) {
throw new BusinessException("配置键已存在");
}
config.setId(SnowflakeIdGenerator.getInstance().nextId());
config.setCreateTime(LocalDateTime.now());
config.setUpdateTime(LocalDateTime.now());
int count = systemConfigMapper.insert(config);
return count > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = "systemConfig", allEntries = true)
public Boolean updateConfig(String key, SystemConfig config) {
log.info("更新配置:key={}", key);
SystemConfig existConfig = systemConfigMapper.selectByConfigKey(key);
if (existConfig == null) {
throw new BusinessException("配置不存在");
}
existConfig.setConfigValue(config.getConfigValue());
existConfig.setDescription(config.getDescription());
existConfig.setCategory(config.getCategory());
existConfig.setIsPublic(config.getIsPublic());
existConfig.setUpdateTime(LocalDateTime.now());
int count = systemConfigMapper.updateById(existConfig);
return count > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
@CacheEvict(value = "systemConfig", allEntries = true)
public Boolean deleteConfig(String key) {
log.info("删除配置:key={}", key);
SystemConfig existConfig = systemConfigMapper.selectByConfigKey(key);
if (existConfig == null) {
throw new BusinessException("配置不存在");
}
int count = systemConfigMapper.deleteById(existConfig.getId());
return count > 0;
}
@Override
public List<SystemConfig> getConfigsByCategory(String category) {
log.info("按分类获取配置:category={}", category);
if (!StringUtils.hasText(category)) {
throw new BusinessException("配置分类不能为空");
}
return systemConfigMapper.selectByCategory(category);
}
@Override
@Cacheable(value = "publicConfigs")
public Map<String, String> getPublicConfigs() {
log.info("获取公开配置");
LambdaQueryWrapper<SystemConfig> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(SystemConfig::getIsPublic, 1);
List<SystemConfig> configs = systemConfigMapper.selectList(wrapper);
Map<String, String> result = new HashMap<>();
for (SystemConfig config : configs) {
result.put(config.getConfigKey(), config.getConfigValue());
}
return result;
}
}9.3 通知服务
创建接口 kb-foundation/src/main/java/com/knowledge/base/foundation/service/NotificationService.java:
package com.knowledge.base.foundation.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.foundation.dto.NotificationDTO;
import com.knowledge.base.foundation.dto.NotificationQueryDTO;
import com.knowledge.base.foundation.entity.Notification;
import com.knowledge.base.foundation.vo.NotificationVO;
/**
* 通知Service接口
*
* @author 苏三
* @since 1.0.0
*/
public interface NotificationService {
Result<Long> sendNotification(NotificationDTO notificationDTO);
IPage<Notification> pageNotifications(Long current, Long size, Long userId, Integer isRead);
Result<IPage<NotificationVO>> getNotifications(NotificationQueryDTO queryDTO);
Notification getNotificationById(Long id);
Boolean sendNotification(Notification notification);
Result<Boolean> markAsRead(Long id);
Result<Boolean> markAllAsRead(Long userId);
Result<Boolean> deleteNotification(Long id);
Result<Long> getUnreadCount(Long userId);
}创建实现类 kb-foundation/src/main/java/com/knowledge/base/foundation/service/impl/NotificationServiceImpl.java:
package com.knowledge.base.foundation.service.impl;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.common.exception.BusinessException;
import com.knowledge.base.common.result.PageParam;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.common.utils.SnowflakeIdGenerator;
import com.knowledge.base.foundation.dto.NotificationDTO;
import com.knowledge.base.foundation.dto.NotificationQueryDTO;
import com.knowledge.base.foundation.entity.Notification;
import com.knowledge.base.foundation.mapper.NotificationMapper;
import com.knowledge.base.foundation.service.NotificationService;
import com.knowledge.base.foundation.vo.NotificationVO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@Service
public class NotificationServiceImpl extends ServiceImpl<NotificationMapper, Notification> implements NotificationService {
@Resource
private NotificationMapper notificationMapper;
@Override
@Transactional(rollbackFor = Exception.class)
public Result<Long> sendNotification(NotificationDTO notificationDTO) {
log.info("发送通知:userId={}, type={}", notificationDTO.getUserId(), notificationDTO.getNotificationType());
if (notificationDTO.getUserId() == null) {
throw new BusinessException("接收用户ID不能为空");
}
if (!StringUtils.hasText(notificationDTO.getNotificationType())) {
throw new BusinessException("通知类型不能为空");
}
if (!StringUtils.hasText(notificationDTO.getTitle())) {
throw new BusinessException("通知标题不能为空");
}
if (!StringUtils.hasText(notificationDTO.getContent())) {
throw new BusinessException("通知内容不能为空");
}
Notification notification = new Notification();
BeanUtil.copyProperties(notificationDTO, notification);
notification.setId(SnowflakeIdGenerator.getInstance().nextId());
if (notification.getIsRead() == null) {
notification.setIsRead(0);
}
notification.setCreateTime(LocalDateTime.now());
int count = notificationMapper.insert(notification);
if (count <= 0) {
throw new BusinessException("发送通知失败");
}
log.info("通知发送成功:notificationId={}", notification.getId());
return Result.success(notification.getId());
}
@Override
public IPage<Notification> pageNotifications(Long current, Long size, Long userId, Integer isRead) {
log.info("分页查询通知:current={}, size={}, userId={}, isRead={}", current, size, userId, isRead);
LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();
if (userId != null) {
wrapper.eq(Notification::getUserId, userId);
}
if (isRead != null) {
wrapper.eq(Notification::getIsRead, isRead);
}
wrapper.orderByDesc(Notification::getCreateTime);
Page<Notification> page = new Page<>(current, size);
return notificationMapper.selectPage(page, wrapper);
}
@Override
public Result<IPage<NotificationVO>> getNotifications(NotificationQueryDTO queryDTO) {
log.info("查询通知列表:userId={}", queryDTO.getUserId());
LambdaQueryWrapper<Notification> wrapper = new LambdaQueryWrapper<>();
if (queryDTO.getUserId() == null) {
throw new BusinessException("用户ID不能为空");
}
wrapper.eq(Notification::getUserId, queryDTO.getUserId());
if (StringUtils.hasText(queryDTO.getNotificationType())) {
wrapper.eq(Notification::getNotificationType, queryDTO.getNotificationType());
}
if (queryDTO.getIsRead() != null) {
wrapper.eq(Notification::getIsRead, queryDTO.getIsRead());
}
if (StringUtils.hasText(queryDTO.getStartTime())) {
wrapper.ge(Notification::getCreateTime, queryDTO.getStartTime());
}
if (StringUtils.hasText(queryDTO.getEndTime())) {
wrapper.le(Notification::getCreateTime, queryDTO.getEndTime());
}
wrapper.orderByDesc(Notification::getCreateTime);
PageParam pageParam = queryDTO;
Page<Notification> page = new Page<>(pageParam.getCurrent(), pageParam.getSize());
IPage<Notification> notificationPage = notificationMapper.selectPage(page, wrapper);
IPage<NotificationVO> voPage = notificationPage.convert(notification -> BeanUtil.copyProperties(notification, NotificationVO.class));
return Result.success(voPage);
}
@Override
public Notification getNotificationById(Long id) {
log.info("查询通知详情:id={}", id);
return notificationMapper.selectById(id);
}
@Override
@Transactional(rollbackFor = Exception.class)
public Boolean sendNotification(Notification notification) {
log.info("发送通知:userId={}, title={}", notification.getUserId(), notification.getTitle());
if (notification.getUserId() == null) {
throw new BusinessException("接收用户ID不能为空");
}
notification.setId(SnowflakeIdGenerator.getInstance().nextId());
if (notification.getIsRead() == null) {
notification.setIsRead(0);
}
notification.setCreateTime(LocalDateTime.now());
int count = notificationMapper.insert(notification);
return count > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result<Boolean> markAsRead(Long id) {
log.info("标记通知已读:notificationId={}", id);
if (id == null) {
throw new BusinessException("通知ID不能为空");
}
Notification notification = notificationMapper.selectById(id);
if (notification == null) {
throw new BusinessException("通知不存在");
}
LambdaUpdateWrapper<Notification> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(Notification::getId, id)
.set(Notification::getIsRead, 1)
.set(Notification::getReadTime, LocalDateTime.now());
int count = notificationMapper.update(null, updateWrapper);
return Result.success(count > 0);
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result<Boolean> markAllAsRead(Long userId) {
log.info("标记所有通知已读:userId={}", userId);
if (userId == null) {
throw new BusinessException("用户ID不能为空");
}
LambdaUpdateWrapper<Notification> updateWrapper = new LambdaUpdateWrapper<>();
updateWrapper.eq(Notification::getUserId, userId)
.eq(Notification::getIsRead, 0)
.set(Notification::getIsRead, 1)
.set(Notification::getReadTime, LocalDateTime.now());
int count = notificationMapper.update(null, updateWrapper);
log.info("已标记{}条通知为已读", count);
return Result.success(true);
}
@Override
@Transactional(rollbackFor = Exception.class)
public Result<Boolean> deleteNotification(Long id) {
log.info("删除通知:notificationId={}", id);
if (id == null) {
throw new BusinessException("通知ID不能为空");
}
int count = notificationMapper.deleteById(id);
return Result.success(count > 0);
}
@Override
public Result<Long> getUnreadCount(Long userId) {
log.info("获取未读通知数量:userId={}", userId);
if (userId == null) {
throw new BusinessException("用户ID不能为空");
}
Long count = notificationMapper.countUnreadByUserId(userId);
return Result.success(count);
}
}9.4 操作日志服务
创建接口 kb-foundation/src/main/java/com/knowledge/base/foundation/service/OperationLogService.java:
package com.knowledge.base.foundation.service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.foundation.entity.OperationLog;
import java.time.LocalDateTime;
import java.util.Map;
public interface OperationLogService {
IPage<OperationLog> pageLogs(Long current, Long size, String module, String operationType, String username, LocalDateTime startTime, LocalDateTime endTime);
OperationLog getLogById(Long id);
Map<String, Object> getStatistics(LocalDateTime startTime, LocalDateTime endTime);
Integer deleteLogsBeforeDate(LocalDateTime beforeDate);
}创建实现类 kb-foundation/src/main/java/com/knowledge/base/foundation/service/impl/OperationLogServiceImpl.java:
package com.knowledge.base.foundation.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.knowledge.base.foundation.entity.OperationLog;
import com.knowledge.base.foundation.mapper.OperationLogMapper;
import com.knowledge.base.foundation.service.OperationLogService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Map;
@Slf4j
@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {
@Resource
private OperationLogMapper operationLogMapper;
private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
public IPage<OperationLog> pageLogs(Long current, Long size, String module, String operationType, String username, LocalDateTime startTime, LocalDateTime endTime) {
log.info("分页查询操作日志:current={}, size={}, module={}, operationType={}, username={}", current, size, module, operationType, username);
LambdaQueryWrapper<OperationLog> wrapper = new LambdaQueryWrapper<>();
if (StringUtils.hasText(module)) {
wrapper.eq(OperationLog::getModule, module);
}
if (StringUtils.hasText(operationType)) {
wrapper.eq(OperationLog::getOperationType, operationType);
}
if (StringUtils.hasText(username)) {
wrapper.eq(OperationLog::getUsername, username);
}
if (startTime != null) {
wrapper.ge(OperationLog::getCreateTime, startTime);
}
if (endTime != null) {
wrapper.le(OperationLog::getCreateTime, endTime);
}
wrapper.orderByDesc(OperationLog::getCreateTime);
Page<OperationLog> page = new Page<>(current, size);
return operationLogMapper.selectPage(page, wrapper);
}
@Override
public OperationLog getLogById(Long id) {
log.info("查询操作日志详情:id={}", id);
return operationLogMapper.selectById(id);
}
@Override
public Map<String, Object> getStatistics(LocalDateTime startTime, LocalDateTime endTime) {
log.info("获取操作日志统计:startTime={}, endTime={}", startTime, endTime);
return null;
}
@Override
@Transactional(rollbackFor = Exception.class)
public Integer deleteLogsBeforeDate(LocalDateTime beforeDate) {
log.info("删除指定日期前的日志:beforeDate={}", beforeDate);
if (beforeDate == null) {
return 0;
}
String dateStr = beforeDate.format(FORMATTER);
int count = operationLogMapper.deleteBeforeDate(dateStr);
log.info("已删除{}条操作日志", count);
return count;
}
}十一、控制器层
10.1 字典管理控制器
创建 kb-foundation/src/main/java/com/knowledge/base/foundation/controller/DictController.java:
package com.knowledge.base.foundation.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.foundation.entity.Dict;
import com.knowledge.base.foundation.entity.DictData;
import com.knowledge.base.foundation.service.DictService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 字典Controller
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@RestController
@RequestMapping("/dicts")
@Tag(name = "字典管理", description = "字典数据管理接口")
public class DictController {
@Resource
private DictService dictService;
/**
* 分页查询字典类型列表
*
* @param current 当前页
* @param size 每页大小
* @param keyword 搜索关键词
* @return 字典分页信息
*/
@GetMapping
@Operation(summary = "分页查询字典", description = "分页查询字典类型列表")
public Result<IPage<Dict>> pageDicts(
@Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
@Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
@Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword) {
log.info("分页查询字典请求:current={}, size={}, keyword={}", current, size, keyword);
IPage<Dict> page = dictService.pageDicts(current, size, keyword);
return Result.success(page);
}
/**
* 根据字典编码查询字典详情
*
* @param code 字典编码
* @return 字典详情
*/
@GetMapping("/{code}")
@Operation(summary = "查询字典详情", description = "根据字典编码查询字典详情")
public Result<Dict> getDictByCode(
@Parameter(description = "字典编码", required = true)
@PathVariable String code) {
log.info("查询字典详情请求:code={}", code);
Dict dict = dictService.getDictByCode(code);
return Result.success(dict);
}
/**
* 获取字典数据列表
*
* @param code 字典编码
* @return 字典数据列表
*/
@GetMapping("/{code}/data")
@Operation(summary = "获取字典数据", description = "根据字典编码获取字典数据列表")
public Result<List<DictData>> getDictData(
@Parameter(description = "字典编码", required = true)
@PathVariable String code) {
log.info("获取字典数据请求:code={}", code);
List<DictData> dataList = dictService.getDictData(code);
return Result.success(dataList);
}
/**
* 创建字典
*
* @param dict 字典信息
* @return 是否成功
*/
@PostMapping
@Operation(summary = "创建字典", description = "创建新的字典类型")
public Result<Boolean> createDict(@Valid @RequestBody Dict dict) {
log.info("创建字典请求:code={}, name={}", dict.getDictCode(), dict.getDictName());
Boolean success = dictService.createDict(dict);
return Result.success("创建字典成功", success);
}
/**
* 更新字典
*
* @param code 字典编码
* @param dict 字典信息
* @return 是否成功
*/
@PutMapping("/{code}")
@Operation(summary = "更新字典", description = "更新字典类型信息")
public Result<Boolean> updateDict(
@Parameter(description = "字典编码", required = true)
@PathVariable String code,
@Valid @RequestBody Dict dict) {
log.info("更新字典请求:code={}", code);
Boolean success = dictService.updateDict(code, dict);
return Result.success("更新字典成功", success);
}
/**
* 删除字典
*
* @param code 字典编码
* @return 是否成功
*/
@DeleteMapping("/{code}")
@Operation(summary = "删除字典", description = "根据字典编码删除字典")
public Result<Boolean> deleteDict(
@Parameter(description = "字典编码", required = true)
@PathVariable String code) {
log.info("删除字典请求:code={}", code);
Boolean success = dictService.deleteDict(code);
return Result.success("删除字典成功", success);
}
/**
* 添加字典数据
*
* @param code 字典编码
* @param dictData 字典数据
* @return 是否成功
*/
@PostMapping("/{code}/data")
@Operation(summary = "添加字典数据", description = "为指定字典添加数据项")
public Result<Boolean> addDictData(
@Parameter(description = "字典编码", required = true)
@PathVariable String code,
@Valid @RequestBody DictData dictData) {
log.info("添加字典数据请求:code={}, label={}", code, dictData.getDictLabel());
Boolean success = dictService.addDictData(code, dictData);
return Result.success("添加字典数据成功", success);
}
/**
* 更新字典数据
*
* @param code 字典编码
* @param dictData 字典数据
* @return 是否成功
*/
@PutMapping("/{code}/data")
@Operation(summary = "更新字典数据", description = "更新字典数据项")
public Result<Boolean> updateDictData(
@Parameter(description = "字典编码", required = true)
@PathVariable String code,
@Valid @RequestBody DictData dictData) {
log.info("更新字典数据请求:code={}, id={}", code, dictData.getId());
Boolean success = dictService.updateDictData(code, dictData);
return Result.success("更新字典数据成功", success);
}
/**
* 删除字典数据
*
* @param code 字典编码
* @param id 数据ID
* @return 是否成功
*/
@DeleteMapping("/{code}/data/{id}")
@Operation(summary = "删除字典数据", description = "删除指定的字典数据项")
public Result<Boolean> deleteDictData(
@Parameter(description = "字典编码", required = true)
@PathVariable String code,
@Parameter(description = "数据ID", required = true)
@PathVariable Long id) {
log.info("删除字典数据请求:code={}, id={}", code, id);
Boolean success = dictService.deleteDictData(code, id);
return Result.success("删除字典数据成功", success);
}
}10.2 系统配置控制器
创建 kb-foundation/src/main/java/com/knowledge/base/foundation/controller/SystemConfigController.java:
package com.knowledge.base.foundation.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.foundation.entity.SystemConfig;
import com.knowledge.base.foundation.service.SystemConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.Map;
/**
* 系统配置Controller
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@RestController
@RequestMapping("/config")
@Tag(name = "系统配置管理", description = "系统配置管理接口")
public class SystemConfigController {
@Resource
private SystemConfigService systemConfigService;
/**
* 分页查询配置列表
*
* @param current 当前页
* @param size 每页大小
* @param category 配置分类
* @return 配置分页信息
*/
@GetMapping
@Operation(summary = "分页查询配置", description = "分页查询系统配置列表")
public Result<IPage<SystemConfig>> pageConfigs(
@Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
@Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
@Parameter(description = "配置分类") @RequestParam(required = false) String category) {
log.info("分页查询配置请求:current={}, size={}, category={}", current, size, category);
IPage<SystemConfig> page = systemConfigService.pageConfigs(current, size, category);
return Result.success(page);
}
/**
* 根据配置键查询配置项
*
* @param key 配置键
* @return 配置信息
*/
@GetMapping("/{key}")
@Operation(summary = "查询配置项", description = "根据配置键查询配置项")
public Result<SystemConfig> getConfigByKey(
@Parameter(description = "配置键", required = true)
@PathVariable String key) {
log.info("查询配置项请求:key={}", key);
SystemConfig config = systemConfigService.getConfigByKey(key);
return Result.success(config);
}
/**
* 创建配置
*
* @param config 配置信息
* @return 是否成功
*/
@PostMapping
@Operation(summary = "创建配置", description = "创建新的系统配置")
public Result<Boolean> createConfig(@Valid @RequestBody SystemConfig config) {
log.info("创建配置请求:key={}", config.getConfigKey());
Boolean success = systemConfigService.createConfig(config);
return Result.success("创建配置成功", success);
}
/**
* 更新配置
*
* @param key 配置键
* @param config 配置信息
* @return 是否成功
*/
@PutMapping("/{key}")
@Operation(summary = "更新配置", description = "更新系统配置")
public Result<Boolean> updateConfig(
@Parameter(description = "配置键", required = true)
@PathVariable String key,
@Valid @RequestBody SystemConfig config) {
log.info("更新配置请求:key={}", key);
Boolean success = systemConfigService.updateConfig(key, config);
return Result.success("更新配置成功", success);
}
/**
* 删除配置
*
* @param key 配置键
* @return 是否成功
*/
@DeleteMapping("/{key}")
@Operation(summary = "删除配置", description = "根据配置键删除配置")
public Result<Boolean> deleteConfig(
@Parameter(description = "配置键", required = true)
@PathVariable String key) {
log.info("删除配置请求:key={}", key);
Boolean success = systemConfigService.deleteConfig(key);
return Result.success("删除配置成功", success);
}
/**
* 按分类获取配置
*
* @param category 配置分类
* @return 配置列表
*/
@GetMapping("/category/{category}")
@Operation(summary = "按分类获取配置", description = "根据配置分类获取配置列表")
public Result<List<SystemConfig>> getConfigsByCategory(
@Parameter(description = "配置分类", required = true)
@PathVariable String category) {
log.info("按分类获取配置请求:category={}", category);
List<SystemConfig> configs = systemConfigService.getConfigsByCategory(category);
return Result.success(configs);
}
/**
* 获取公开配置
*
* @return 公开配置Map
*/
@GetMapping("/public")
@Operation(summary = "获取公开配置", description = "获取所有公开的系统配置")
public Result<Map<String, String>> getPublicConfigs() {
log.info("获取公开配置请求");
Map<String, String> configs = systemConfigService.getPublicConfigs();
return Result.success(configs);
}
}10.3 通知管理控制器
创建 kb-foundation/src/main/java/com/knowledge/base/foundation/controller/NotificationController.java:
package com.knowledge.base.foundation.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.foundation.entity.Notification;
import com.knowledge.base.foundation.service.NotificationService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
@Slf4j
@RestController
@RequestMapping("/notifications")
@Tag(name = "通知管理", description = "系统通知管理接口")
public class NotificationController {
@Resource
private NotificationService notificationService;
@GetMapping
@Operation(summary = "分页查询通知", description = "分页查询通知列表")
public Result<IPage<Notification>> pageNotifications(
@Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
@Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
@Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
@Parameter(description = "是否已读") @RequestParam(required = false) Integer isRead) {
log.info("分页查询通知请求:current={}, size={}, userId={}, isRead={}", current, size, userId, isRead);
IPage<Notification> page = notificationService.pageNotifications(current, size, userId, isRead);
return Result.success(page);
}
@GetMapping("/{id}")
@Operation(summary = "查询通知详情", description = "根据通知ID查询通知详情")
public Result<Notification> getNotificationById(
@Parameter(description = "通知ID", required = true)
@PathVariable Long id) {
log.info("查询通知详情请求:id={}", id);
Notification notification = notificationService.getNotificationById(id);
return Result.success(notification);
}
@PostMapping
@Operation(summary = "发送通知", description = "创建新通知")
public Result<Boolean> sendNotification(@Valid @RequestBody Notification notification) {
log.info("发送通知请求:userId={}, title={}", notification.getUserId(), notification.getTitle());
Boolean success = notificationService.sendNotification(notification);
return Result.success("发送通知成功", success);
}
@PutMapping("/{id}/read")
@Operation(summary = "标记已读", description = "标记通知为已读")
public Result<Boolean> markAsRead(
@Parameter(description = "通知ID", required = true)
@PathVariable Long id) {
log.info("标记通知已读请求:id={}", id);
return notificationService.markAsRead(id);
}
@PutMapping("/read-all")
@Operation(summary = "全部标记已读", description = "将用户所有未读通知标记为已读")
public Result<Boolean> markAllAsRead(
@Parameter(description = "用户ID", required = true)
@RequestParam Long userId) {
log.info("全部标记已读请求:userId={}", userId);
return notificationService.markAllAsRead(userId);
}
@DeleteMapping("/{id}")
@Operation(summary = "删除通知", description = "根据通知ID删除通知")
public Result<Boolean> deleteNotification(
@Parameter(description = "通知ID", required = true)
@PathVariable Long id) {
log.info("删除通知请求:id={}", id);
return notificationService.deleteNotification(id);
}
@GetMapping("/unread-count")
@Operation(summary = "获取未读数量", description = "获取用户未读通知数量")
public Result<Long> getUnreadCount(
@Parameter(description = "用户ID", required = true)
@RequestParam Long userId) {
log.info("获取未读数量请求:userId={}", userId);
return notificationService.getUnreadCount(userId);
}
}10.4 操作日志控制器
创建 kb-foundation/src/main/java/com/knowledge/base/foundation/controller/OperationLogController.java:
package com.knowledge.base.foundation.controller;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.knowledge.base.common.result.Result;
import com.knowledge.base.foundation.entity.OperationLog;
import com.knowledge.base.foundation.service.OperationLogService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.util.Map;
/**
* 操作日志Controller
*
* @author 苏三
* @since 1.0.0
*/
@Slf4j
@RestController
@RequestMapping("/logs")
@Tag(name = "操作日志管理", description = "操作日志管理接口")
public class OperationLogController {
@Resource
private OperationLogService operationLogService;
/**
* 分页查询日志列表
*
* @param current 当前页
* @param size 每页大小
* @param module 模块名称
* @param operationType 操作类型
* @param username 用户名
* @param startTime 开始时间
* @param endTime 结束时间
* @return 日志分页信息
*/
@GetMapping
@Operation(summary = "分页查询日志", description = "分页查询操作日志列表")
public Result<IPage<OperationLog>> pageLogs(
@Parameter(description = "当前页") @RequestParam(defaultValue = "1") Long current,
@Parameter(description = "每页大小") @RequestParam(defaultValue = "10") Long size,
@Parameter(description = "模块名称") @RequestParam(required = false) String module,
@Parameter(description = "操作类型") @RequestParam(required = false) String operationType,
@Parameter(description = "用户名") @RequestParam(required = false) String username,
@Parameter(description = "开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
log.info("分页查询日志请求:current={}, size={}, module={}, operationType={}, username={}",
current, size, module, operationType, username);
IPage<OperationLog> page = operationLogService.pageLogs(current, size, module,
operationType, username, startTime, endTime);
return Result.success(page);
}
/**
* 根据ID查询日志详情
*
* @param id 日志ID
* @return 日志详情
*/
@GetMapping("/{id}")
@Operation(summary = "查询日志详情", description = "根据日志ID查询日志详情")
public Result<OperationLog> getLogById(
@Parameter(description = "日志ID", required = true)
@PathVariable Long id) {
log.info("查询日志详情请求:id={}", id);
OperationLog log = operationLogService.getLogById(id);
return Result.success(log);
}
/**
* 获取日志统计信息
*
* @param startTime 开始时间
* @param endTime 结束时间
* @return 统计信息
*/
@GetMapping("/statistics")
@Operation(summary = "获取日志统计", description = "获取操作日志统计信息")
public Result<Map<String, Object>> getStatistics(
@Parameter(description = "开始时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime startTime,
@Parameter(description = "结束时间") @RequestParam(required = false)
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime endTime) {
log.info("获取日志统计请求:startTime={}, endTime={}", startTime, endTime);
Map<String, Object> statistics = operationLogService.getStatistics(startTime, endTime);
return Result.success(statistics);
}
/**
* 删除指定日期前的日志
*
* @param beforeDate 指定日期
* @return 删除数量
*/
@DeleteMapping("/before-date")
@Operation(summary = "删除历史日志", description = "删除指定日期前的操作日志")
public Result<Integer> deleteLogsBeforeDate(
@Parameter(description = "指定日期", required = true)
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime beforeDate) {
log.info("删除历史日志请求:beforeDate={}", beforeDate);
Integer count = operationLogService.deleteLogsBeforeDate(beforeDate);
return Result.success("删除成功", count);
}
}十二、数据初始化
11.1 执行数据库初始化脚本
在项目根目录下执行初始化脚本:
mysql -u root -p < sql/init_kb_foundation.sql11.2 验证数据
检查数据库表是否创建成功:
mysql -u root -p kb_foundation -e "SHOW TABLES;"预期输出:
+-------------------------+
| Tables_in_kb_foundation |
+-------------------------+
| kb_dict |
| kb_dict_data |
| kb_notification |
| kb_operation_log |
| kb_system_config |
+-------------------------+十三、测试验证
12.1 启动服务
# 方式一:使用Maven启动
cd kb-foundation
mvn spring-boot:run
# 方式二:使用IDE启动
# 在IDEA中打开FoundationApplication.java,点击运行启动成功后,控制台输出:
========================================
基础服务启动成功!
服务名称: kb-foundation
服务端口: 8089
API文档: http://localhost:8089/api/foundation/doc.html
Druid监控: http://localhost:8089/api/foundation/druid/
========================================12.2 访问API文档
打开浏览器访问:http://localhost:8089/api/foundation/doc.html
12.3 测试接口
测试字典管理接口
创建字典类型:
curl -X POST http://localhost:8089/api/foundation/dicts \
-H "Content-Type: application/json" \
-d '{
"dictCode": "test_dict",
"dictName": "测试字典",
"dictType": "TEST",
"description": "测试用字典",
"sort": 0,
"status": 1
}'获取字典数据:
curl http://localhost:8089/api/foundation/dicts/test_dict/data测试系统配置接口
创建配置:
curl -X POST http://localhost:8089/api/foundation/config \
-H "Content-Type: application/json" \
-d '{
"configKey": "test.config",
"configValue": "test_value",
"configType": "string",
"category": "TEST",
"description": "测试配置",
"isPublic": 1
}'获取公开配置:
curl http://localhost:8089/api/foundation/config/public测试通知接口
发送通知:
curl -X POST http://localhost:8089/api/foundation/notifications \
-H "Content-Type: application/json" \
-d '{
"userId": 1,
"userName": "测试用户",
"notificationType": "system",
"title": "测试通知",
"content": "这是一条测试通知",
"link": "/test"
}'获取未读数量:
curl http://localhost:8089/api/foundation/notifications/unread-count?userId=1十四、总结
本文详细介绍了公共基础服务模块的搭建过程,涵盖了以下核心内容:
已完成功能
| 模块 | 功能 | 说明 |
|---|---|---|
| 字典管理 | CRUD、数据管理 | 提供系统字典数据管理 |
| 系统配置 | CRUD、分类查询、缓存 | 支持多类型配置,带缓存 |
| 通知管理 | 发送、标记已读、未读统计 | 支持多种通知类型 |
| 操作日志 | 记录、查询、统计、清理 | 完整的审计日志功能 |
| 基础设施 | Redis、RabbitMQ、WebSocket | 支持缓存、消息队列、实时通信 |