1. AOP 简介
- 定义:面向切面编程(Aspect-Oriented Programming)是一种编程范式,允许在不修改核心业务逻辑的情况下,将横切关注点与业务逻辑分离。
- 目的:提高代码的可读性和维护性,减少重复代码。
- 使用场景:日志记录、异常处理、事务管理、安全验证、性能监控等。
2. AOP 的核心概念
- 切面(Aspect):封装横切关注点的模块,如日志记录功能。
- 连接点(JoinPoint):程序执行的某个特定点,比如方法的调用或异常的抛出。
- 通知(Advice):切面在连接点执行的操作,常见的类型包括前置通知、后置通知、环绕通知、异常通知等。
- 切入点(Pointcut):定义在哪些连接点上应用通知,通过表达式来进行匹配。
- 织入(Weaving):将切面应用到目标对象的过程。
3. AOP 的使用场景
- 日志管理:在方法执行前后记录日志。
- 性能监控:监控方法执行的时间。
- 安全控制:在方法执行前进行权限校验。
- 事务管理:确保方法执行时事务的一致性。
4. Spring AOP 实现
- Spring AOP 是基于动态代理的实现,支持基于接口和类的代理。
- 通过 Spring AOP 的
@Aspect
注解可以轻松实现切面。
5. 核心场景
1.展示如何使用 Spring AOP 来记录日志-(方法执行前后新增日志,一般用于核心方法定位入参和返回结果):
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBeforeMethod(JoinPoint joinPoint) {
System.out.println("Method: " + joinPoint.getSignature().getName() + " is about to be called");
}
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
public void logAfterMethod(JoinPoint joinPoint, Object result) {
System.out.println("Method: " + joinPoint.getSignature().getName() + " has returned with result: " + result);
}
}
场景2 结合 Redis 实现幂等性保障
幂等性是指某个操作无论执行多少次,结果都是相同的。这在支付系统、订单系统等场景中尤为重要。结合 AOP 和 Redis,可以通过唯一标识和过期机制实现接口的幂等性。
也可以在切面里通过数据库层面进行幂等,需要对幂等字段增加唯一索引。这样如果在高频接口会增加db压力,建议是把db幂等放到方法里面。redis幂等放外面。双重保证。
实现步骤:
-
在请求中引入唯一标识:可以在请求中携带一个唯一的
requestId
。 -
利用 Redis 存储请求标识:在执行方法前,先检查 Redis 中是否已有相同的
requestId
,如果存在则拒绝执行操作。 -
执行方法后删除标识(可选):根据实际需求决定是否删除
requestId
。
代码示例:
@Aspect
@Component
public class IdempotentAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
// 定义幂等的切入点
@Pointcut("@annotation(com.example.annotation.Idempotent)")
public void idempotentPointcut() {}
@Around("idempotentPointcut() && args(requestId,..)")
public Object ensureIdempotency(ProceedingJoinPoint joinPoint, String requestId) throws Throwable {
String key = "idempotent:" + requestId;
// 尝试将 requestId 存入 Redis,过期时间为 5 分钟
Boolean isAbsent = redisTemplate.opsForValue().setIfAbsent(key, "1", 5, TimeUnit.MINUTES);
if (Boolean.FALSE.equals(isAbsent)) {
throw new IllegalStateException("请求重复,已拒绝处理");
}
try {
// 执行目标方法
return joinPoint.proceed();
} finally {
// 根据需求,是否需要删除 key
// redisTemplate.delete(key);
}
}
}
自定义注解:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Idempotent {}
通过 Redis 实现幂等性,避免了同一个请求被重复处理,从而保护了业务逻辑的正确性,尤其在网络重试或分布式系统中非常重要。
场景3.记录方法执行时间
一般应用于需要调优的核心方法。记录执行时间长短
监控方法的执行时间是优化性能的重要手段。通过 AOP 和 可以记录方法的执行时间。
代码示例:
@Aspect
@Component
public class MethodExecutionTimeAspect {
@Autowired
private RedisTemplate<String, Long> redisTemplate;
// 定义切入点,监控 service 包下的所有方法
@Pointcut("execution(* com.example.service.*.*(..))")
public void monitorPointcut() {}
@Around("monitorPointcut()")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
// 执行目标方法
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - startTime;
// 记录执行时间到 Redis,key 可以是方法名称
String methodName = joinPoint.getSignature().toShortString();
System.out.println("Method " + methodName + " executed in " + executionTime + "ms");
return proceed;
}
}
6. AOP 的优缺点
-
优点:
- 解耦横切关注点与业务逻辑。
- 代码更简洁、可维护性更高。
-
缺点:
- 可能增加调试难度,特别是当多个切面交织在一起时。
7. 总结
- AOP 是一种强大的编程范式,尤其在需要分离横切关注点的场景中非常有用。
- 在使用 AOP 时,要注意保持切面的简洁,避免过度使用导致代码复杂化。