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

一、目标场景

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

  • 需要:

    • 防重复点击

    • 不同接口规则不同

    • 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:

    • 随时切
相关推荐
小CC吃豆子21 分钟前
Java数据结构与算法
java·开发语言
晨旭缘22 分钟前
后端日常启动及常用命令(Java)
java·开发语言
CodeAmaz22 分钟前
ArrayList 底层原理
java·arraylist
山峰哥23 分钟前
3000字深度解析:SQL调优如何让数据库查询效率提升10倍
java·服务器·数据库·sql·性能优化·编辑器
tkevinjd24 分钟前
JUC2(多线程中常用的成员方法)
java
天天摸鱼的java工程师30 分钟前
工作中 Java 程序员如何集成 AI?Spring AI、LangChain4j、JBoltAI 实战对比
java·后端
星辰_mya30 分钟前
RockerMQ之commitlog与consumequeue
java·开发语言
__万波__31 分钟前
二十三种设计模式(二十二)--策略模式
java·设计模式·策略模式
不想上班的小吕32 分钟前
采购申请创建(BAPI_PR_CREATE/BAPI_REQUISITION_CREATE)
java·服务器·数据库
专注VB编程开发20年35 分钟前
压栈顺序是反向(从右往左)的,但正因为是反向压栈,所以第一个参数反而离栈顶(ESP)最近。
java·开发语言·算法