使用策略模式+装饰器模式实现接口防重复提交

一、目标场景

  • 提现 / 下单 / 行为记录接口

  • 需要:

    • 防重复点击

    • 不同接口规则不同

    • Redis / 内存都可能用

二、整体设计

@NoRepeatSubmit

AOP(装饰器)

RepeatSubmitStrategy(策略)

Redis / 内存 / Token

每一层职责非常单一

三、第一步:注解

java 复制代码
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NoRepeatSubmit {

    /** 策略类型 */
    String strategy() default "REDIS";

    /** 间隔时间(毫秒) */
    long interval() default 1500;
}

四、第二步:策略模式

1 策略接口

java 复制代码
public interface RepeatSubmitStrategy {

    boolean isRepeat(String key, long interval);
}

2 Redis 实现

java 复制代码
@Component("REDIS")
public class RedisRepeatSubmitStrategy implements RepeatSubmitStrategy {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean isRepeat(String key, long interval) {
        Boolean success = redisTemplate.opsForValue()
                .setIfAbsent(key, "1", interval, TimeUnit.MILLISECONDS);
        return Boolean.FALSE.equals(success);
    }
}

3 内存实现(兜底 / 本地)

java 复制代码
@Component("LOCAL")
public class LocalRepeatSubmitStrategy implements RepeatSubmitStrategy {

    private final Map<String, Long> cache = new ConcurrentHashMap<>();

    @Override
    public boolean isRepeat(String key, long interval) {
        long now = System.currentTimeMillis();
        Long last = cache.put(key, now);
        return last != null && now - last < interval;
    }
}

五、第三步:AOP(装饰器模式)

java 复制代码
@Aspect
@Component
public class NoRepeatSubmitAspect {

    @Autowired
    private Map<String, RepeatSubmitStrategy> strategyMap;

    @Around("@annotation(noRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp,
                          NoRepeatSubmit noRepeatSubmit) throws Throwable {

        String key = buildKey(pjp);
        String strategy = noRepeatSubmit.strategy();
        long interval = noRepeatSubmit.interval();

        RepeatSubmitStrategy handler = strategyMap.get(strategy);

        if (handler.isRepeat(key, interval)) {
            return AjaxResult.error("操作太频繁,请稍后再试");
        }

        return pjp.proceed();
    }

    private String buildKey(ProceedingJoinPoint pjp) {
        // userId + method + 参数摘要
        return pjp.getSignature().toShortString();
    }
}

六、Controller 使用

java 复制代码
@PostMapping("/withdraw")
@NoRepeatSubmit(strategy = "REDIS", interval = 1500)
public AjaxResult withdraw() {
    // 业务逻辑非常干净
    return AjaxResult.success();
}

通过策略模式+装饰器模式的防重复提交实现:

  • Controller 0 if / 0 try-catch

  • 新加规则:

    • 新加一个 Strategy

    • 不动旧代码

  • Redis / 本地 / Token:

    • 随时切
相关推荐
带刺的坐椅16 分钟前
用 ChatModel 构建 LLM 驱动的 Java 应用
java·ai·llm·solon·rag·chatmodel
用户3721574261352 小时前
Java 将 Word 文档转换为 Markdown:基础转换与导出选项详解
java
行者全栈架构师2 小时前
PolarDB + Spring Boot 实战:从自建MySQL到云原生数据库的零停机迁移
java·后端·架构
karry_k18 小时前
MyBatis批量insert-select踩坑:useGeneratedKeys=true 可能让PostgreSQL返回大量插入结果
java·后端
karry_k18 小时前
PostgreSQL 在 MyBatis 中执行正常 SQL 失效:一次 DELETE USING 踩坑记录
java·后端
SamDeepThinking1 天前
从源码到代码:MyBatis-Flex 与 MyBatis-Plus 的逐项对比
java·后端·程序员
她的男孩1 天前
Spring Boot 接 Flowable 工作流:用 3 个注解搭一个请假审批流程
java·后端·架构
荣码1 天前
LLM结构化输出:让AI返回JSON而不是废话,我踩了4个坑
java·python
plainGeekDev1 天前
Gson → kotlinx.serialization
android·java·kotlin