package com.example.demo.RabbitMQ; import com.example.demo.Util.SecurityUtils; import com.example.demo.config.RabbitMQConfig; import com.example.demo.config.interfac.Message; import com.example.demo.domain.DTO.MessageDTO; import com.example.demo.mapper.coin.OperationLogMapper; import com.example.demo.mapper.coin.UserMapper; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; /** * @program: GOLD * @ClassName CashCollectionAspect * @description: * @author: huangqizhen * @create: 2025−11-14 19:10 * @Version 1.0 **/ @Aspect @Component @Slf4j public class CashCollectionAspect { @Autowired private RabbitTemplate rabbitTemplate; @Autowired private UserMapper userMapper; @Autowired private OperationLogMapper operationLogMapper; @Around("@annotation(com.example.demo.config.interfac.Message)") public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable { long startTime = System.currentTimeMillis(); MethodSignature signature = (MethodSignature) joinPoint.getSignature(); String methodName = signature.getName(); String className = signature.getDeclaringTypeName(); Object[] args = joinPoint.getArgs(); Message logAnnotation = signature.getMethod().getAnnotation(Message.class); String action = logAnnotation.value(); // ✅ 使用 Spring Security 获取真实用户 String username = SecurityUtils.getCurrentUsername(); Integer userId = SecurityUtils.getCurrentUserId(); String name = userMapper.selectUserByJwcode(Integer.valueOf(username)).getName(); // 添加空值检查 if (userId == null) { log.warn("无法获取当前用户ID,使用默认值 -1"); userId = -1; // 或者使用其他默认值 } ObjectMapper mapper = new ObjectMapper(); String argsJson = "[]"; try { argsJson = mapper.writeValueAsString(args); } catch (Exception e) { argsJson = "serialize failed"; } Object result; try { result = joinPoint.proceed(); } catch (Exception e) { log.error("方法执行异常: {}", e.getMessage()); throw e; } long duration = System.currentTimeMillis() - startTime; // ✅ 构造日志消息 DTO MessageDTO messageDTO = new MessageDTO(); messageDTO.setJwcode(Integer.valueOf(username)); messageDTO.setName(name); messageDTO.setTitle(action); messageDTO.setDesc(username+"有一条消息需要处理"); // operationLogMapper.insertMessage(messageDTO); // ✅ 发送消息到 RabbitMQ(不等待) try { rabbitTemplate.convertAndSend(RabbitMQConfig.CASH_COLLECTION_EXCHANGE, "cash.collection.save", messageDTO); log.info("📩 日志消息已发送到 RabbitMQ: {}", action); } catch (Exception e) { log.error("发送日志消息到 RabbitMQ 失败", e); } log.info("✅ AOP 拦截完成: {} 执行 [{}] 耗时 {}ms", username, action, duration); return result; } }