oa软件下载,郑州seo优化顾问,怎么才可以做网站,微信管理系统免费版在分布式系统中#xff0c;接口幂等性是确保操作一致性的关键特性。
啥是幂等性
幂等性 指的是在给定的条件下#xff0c;无论操作执行多少次#xff0c;其结果都保持不变。在接口设计中#xff0c;幂等性意味着使用相同的参数多次调用接口#xff0c;应产生与单次调用相…在分布式系统中接口幂等性是确保操作一致性的关键特性。
啥是幂等性
幂等性 指的是在给定的条件下无论操作执行多少次其结果都保持不变。在接口设计中幂等性意味着使用相同的参数多次调用接口应产生与单次调用相同的效果。 CRUD操作的幂等性分析 查询Read通常幂等但若依赖可变数据则可能非幂等。 创建Create天然幂等重复创建相同记录应避免或处理。 更新Update理论上幂等但如基于前一状态的增量更新则非幂等。 删除Delete天然幂等重复删除相同记录应直接返回成功。
接口幂等与防抖的区别 防抖防止用户在短时间内重复触发操作通常用于前端。 幂等性确保后端接口在重复调用时保持一致性。
Demo
定义Idempotent注解
Retention(RetentionPolicy.RUNTIME)
Target(ElementType.METHOD)
Documented
public interface Idempotent {String key() default #root.methodName #root.args;int expireTime() default 60; // 过期时间默认60秒TimeUnit timeUnit() default TimeUnit.SECONDS;String info() default 操作过于频繁请稍后再试;boolean delKeyAfterSuccess() default true; // 成功后是否删除key
}
AOP实现幂等性检查
Aspect
Component
public class IdempotentAspect {Autowiredprivate RedisTemplateString, String redisTemplate;Around(annotation(idempotent))public Object around(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {String key generateKey(joinPoint, idempotent);boolean isExecuted redisTemplate.hasKey(key);if (isExecuted) {throw new RuntimeException(idempotent.info());}redisTemplate.opsForValue().set(key, executed, idempotent.expireTime(), idempotent.timeUnit());Object result joinPoint.proceed();if (idempotent.delKeyAfterSuccess()) {redisTemplate.delete(key);}return result;}private String generateKey(JoinPoint joinPoint, Idempotent idempotent) {EvaluationContext context new StandardEvaluationContext();String[] parameterNames ((MethodSignature) joinPoint.getSignature()).getParameterNames();Object[] args joinPoint.getArgs();for (int i 0; i parameterNames.length; i) {context.setVariable(parameterNames[i], args[i]);}return ExpressionUtils.evaluateStringExpression(idempotent.key(), context);}
}
使用Idempotent注解
RestController
public class TestController {PostMapping(/test)Idempotent(expireTime 30, info 请求太频繁请稍后再试, delKeyAfterSuccess true)public ResponseEntity? testMethod(RequestParam String param) {// 业务逻辑...return ResponseEntity.ok(操作成功);}
}
通过定义专用的注解和使用AOP我们能够以一种声明式的方式实现接口幂等性。这种方法不仅代码侵入性低而且易于维护和扩展。
欢迎关注我的公众号“程序员洋哥”原创技术文章第一时间推送。