使用自定义注解实现幂等性控制
实现自定义注解、实现自定义幂等性注解
1、自定义注解
- 添加 Spring AOP 依赖。
<!-- Spring AOP dependency -->
<dependency>
<groupIdorg.springframework.boot</groupId>
<artifactIdspring-boot-starter-aop</artifactId>
</dependency>
- 创建自定义注解。
创建一个新的 Java 注解类,通过@interface
关键字来定义,并可以添加元注解以及属性。
@Target(ElementType.METHOD) //表示作用于方法上
@Retention(RetentionPolicy.RUNTIME) // 表示这个注解在运行时是可见的,这样 AOP 代理才能在运行时读取到这个注解
public @interface CustomLogAnnotation {
String value() default "";
boolean enable() default true;
}
- 编写 AOP 拦截(自定义注解)的逻辑代码。
@Aspect
@Component
public class CustomLogAspect {
@Around("@annotation(customLog)")
public Object logAround(ProceedingJoinPoint joinPoint, CustomLogAnnotation customLog) throws Throwable {
if (customLog.enable()) {
// 方法执行前的处理
System.out.println("Before method execution: " + joinPoint.getSignature().getName());
long start = System.currentTimeMillis();
// 执行目标方法
Object result = joinPoint.proceed();
// 方法执行后的处理
long elapsedTime = System.currentTimeMillis() - start;
System.out.println("After method execution (" + elapsedTime +
"ms): " + customLog.value());
return result;
} else {
return joinPoint.proceed();
}
}
}
- 使用自定义注解。
将自定义注解应用于需要进行日志记录的方法上.
@RestController
public class MyController {
@CustomLogAnnotation(value = "This is a test method", enable = true) //自定义注解
@GetMapping("/test")
public String testMethod() {
// 业务逻辑代码
return "Hello from the annotated method!";
}
}
2、自定义幂等性注解
幂等性判断是指在分布式系统或并发环境中,对于同一操作的多次重复请求,系统的响应结果应该是一致的。简而言之,无论接收到多少次相同的请求,系统的行为和结果都应该是相同的。
下面我们使用拦截器 + Redis
的方式来实现一下自定义幂等性注解,它的实现步骤如下:
1、创建自定义幂等性注解。
2、创建拦截器,实现幂等性逻辑判断。
3、配置拦截规则。
4、使用自定义幂等性注解。
**这样,当有相同的请求 ID 在指定的有效期内再次发起请求时,会被拦截器识别并阻止其重复执行业务逻辑。**
自定义注解被广泛应用于日常开发中,像日志记录、性能监控、权限判断和幂等性判断等功能的实现,使用自定义注解来实现是非常方便的。在 Spring Boot 中,使用 @interface
关键字来定义自定义注解,之后再使用 AOP
或拦截器
的方式实现自定义注解,之后就可以方便的使用自定义注解了。