当前位置: 代码网 > it编程>编程语言>Java > SpringBoot接口防抖实战之防重复提交的5种高级方案

SpringBoot接口防抖实战之防重复提交的5种高级方案

2026年04月07日 Java 我要评论
前言作为一名摸爬滚打八年的 java 开发,我敢说:线上 80% 的 “数据错乱” 故障,都和接口重复提交有关。上周大促,用户疯狂点击下单按钮,导致同一订单被创建了 3 次;去

前言

作为一名摸爬滚打八年的 java 开发,我敢说:线上 80% 的 “数据错乱” 故障,都和接口重复提交有关。上周大促,用户疯狂点击下单按钮,导致同一订单被创建了 3 次;去年支付接口被爬虫高频调用,直接产生了双倍扣款 —— 这些血淋淋的案例告诉我们:接口防抖不是 “可选功能”,而是 “必做防护”。

很多人觉得 “防重复提交不就是前端按钮禁用吗?”—— 太天真了!爬虫、postman 直接调用、网络延迟重发,这些场景前端防护形同虚设。今天就从实战出发,分享 5 种 springboot 接口防抖的高级方案,覆盖单机、分布式、高并发等所有场景,每一种都附可直接复制的代码和八年踩坑总结,让你彻底解决 “手抖党” 和 “恶意刷接口” 的烦恼。

一、先分清:防抖 vs 防重?别再混淆了!

在讲方案前,先澄清两个高频混淆的概念(八年开发见过太多人用错):

  • 接口防抖(debounce) :阻止短时间内重复触发同一接口(比如 1 秒内点 5 次下单),核心是 “限制触发频率”;
  • 接口防重(idempotent) :保证同一请求多次执行结果一致(比如重复支付只扣一次钱),核心是 “结果唯一性”。

本文的方案是 “防抖 + 防重” 结合 —— 既阻止高频重复调用,又保证即使调用多次也不会出问题,真正做到 “双重防护”。

二、5 种高级方案:从单机到分布式,覆盖所有场景

方案 1:基于 redis+lua 脚本(分布式高并发首选)

核心原理

利用 redis 的原子性 + lua 脚本,给接口加 “限时锁”:同一请求标识(比如用户 id + 接口名 + 参数摘要)在指定时间内只能执行一次,超过时间自动释放锁。

为什么用 lua?

redis 单条命令是原子的,但多条命令组合(比如先查 key 是否存在,再 set 值)会有并发问题。lua 脚本能把多步操作打包成原子执行,避免 “竞态条件”—— 这是分布式防重的关键(八年开发踩过的坑:以前用 redis+java 代码判断,高并发下还是会出现重复提交)。

实战代码

  1. 先定义防抖注解(标记需要防重的接口)
import java.lang.annotation.*;
import java.util.concurrent.timeunit;
@target(elementtype.method)
@retention(retentionpolicy.runtime)
@documented
public @interface antiduplicatesubmit {
    // 防抖时间(默认1秒)
    long timeout() default 1;
    // 时间单位(默认秒)
    timeunit unit() default timeunit.seconds;
    // 提示信息
    string message() default "操作过于频繁,请稍后再试!";
}
  1. lua 脚本(原子执行 “查锁 + 加锁”)在resources/lua/anti_duplicate_submit.lua创建脚本:
-- 1. 接收参数:key=请求标识,timeout=过期时间
local key = keys[1]
local timeout = argv[1]
-- 2. 查锁:存在则返回1(重复提交),不存在则加锁返回0
if redis.call('exists', key) == 1 then
    return 1
else
    redis.call('set', key, '1', 'ex', timeout)
    return 0
end
  1. aop 切面(拦截注解,执行 lua 脚本)
import jakarta.annotation.resource;
import jakarta.servlet.http.httpservletrequest;
import lombok.extern.slf4j.slf4j;
import org.aspectj.lang.proceedingjoinpoint;
import org.aspectj.lang.annotation.around;
import org.aspectj.lang.annotation.aspect;
import org.aspectj.lang.reflect.methodsignature;
import org.springframework.core.io.classpathresource;
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.data.redis.core.script.defaultredisscript;
import org.springframework.stereotype.component;
import org.springframework.util.digestutils;
import org.springframework.util.stringutils;
import java.lang.reflect.method;
import java.nio.charset.standardcharsets;
import java.util.collections;
@aspect
@component
@slf4j
public class antiduplicatesubmitaspect {
    @resource
    private stringredistemplate stringredistemplate;
    private final defaultredisscript<long> antiduplicatescript;
    // 初始化lua脚本
    public antiduplicatesubmitaspect() {
        antiduplicatescript = new defaultredisscript<>();
        antiduplicatescript.setlocation(new classpathresource("lua/anti_duplicate_submit.lua"));
        antiduplicatescript.setresulttype(long.class);
    }
    @around("@annotation(com.example.demo.annotation.antiduplicatesubmit)")
    public object around(proceedingjoinpoint joinpoint) throws throwable {
        methodsignature signature = (methodsignature) joinpoint.getsignature();
        method method = signature.getmethod();
        antiduplicatesubmit annotation = method.getannotation(antiduplicatesubmit.class);
        // 3. 生成唯一请求标识(用户id+接口名+参数摘要)
        string requestkey = generaterequestkey(joinpoint, method);
        long timeout = annotation.unit().toseconds(annotation.timeout());
        // 4. 执行lua脚本
        long result = stringredistemplate.execute(
                antiduplicatescript,
                collections.singletonlist(requestkey),
                string.valueof(timeout)
        );
        // 5. 结果判断:1=重复提交,0=正常执行
        if (result != null && result == 1) {
            log.warn("接口重复提交,key:{}", requestkey);
            throw new runtimeexception(annotation.message());
        }
        // 6. 正常执行接口逻辑
        try {
            return joinpoint.proceed();
        } finally {
            // 可选:非幂等接口执行完手动释放锁(幂等接口可依赖自动过期)
            // stringredistemplate.delete(requestkey);
        }
    }
    // 生成唯一请求标识:避免不同用户/不同参数被误判为重复
    private string generaterequestkey(proceedingjoinpoint joinpoint, method method) {
        // 获取用户id(实际项目从token/上下文获取,这里简化)
        string userid = "anonymous"; // 替换为真实用户标识
        // 获取接口名(类名+方法名)
        string methodname = method.getdeclaringclass().getname() + "." + method.getname();
        // 获取参数摘要(避免参数不同但被误判,用md5加密)
        string paramdigest = digestutils.md5digestashex(
                (joinpoint.getargs() != null ? joinpoint.getargs().tostring() : "").getbytes(standardcharsets.utf_8)
        );
        // 拼接key:redis key前缀+用户id+接口名+参数摘要
        return "anti_duplicate:" + userid + ":" + methodname + ":" + paramdigest;
    }
}
  1. 接口使用(只需加注解)
import org.springframework.web.bind.annotation.postmapping;
import org.springframework.web.bind.annotation.requestbody;
import org.springframework.web.bind.annotation.restcontroller;
@restcontroller
public class ordercontroller {
    // 下单接口:1秒内禁止重复提交
    @antiduplicatesubmit(timeout = 1, message = "下单太频繁啦,1秒后再试~")
    @postmapping("/api/order/create")
    public string createorder(@requestbody orderdto orderdto) {
        // 下单逻辑(省略)
        return "下单成功,订单号:" + system.currenttimemillis();
    }
}

八年踩坑提示

  • 过期时间别设太短(比如小于 500ms):网络延迟可能导致正常请求被误判;也别设太长(比如超过 10 秒):用户正常重试会被拦截;
  • 请求标识必须包含 “用户 id”:否则不同用户调用同一接口会被误判为重复;
  • 非幂等接口(比如退款)建议执行完手动释放锁:避免正常流程结束后还占用锁。

适用场景:分布式系统、高并发场景(电商大促、支付接口)

方案 2:基于 token 令牌(前后端联动,最安全)

核心原理

前端请求接口前,先向服务端申请 “唯一令牌”,服务端生成令牌存入 redis;前端带着令牌调用业务接口,服务端验证令牌存在后执行逻辑,并删除令牌(确保只能用一次)。

为什么安全?

令牌是一次性的,且绑定用户,即使接口被爬虫抓取,没有令牌也无法重复提交 —— 这是防御 “恶意刷接口” 的终极方案。

实战代码

  1. token 生成接口(前端先调用获取令牌)
import org.springframework.data.redis.core.stringredistemplate;
import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.restcontroller;
import jakarta.annotation.resource;
import java.util.uuid;
import java.util.concurrent.timeunit;
@restcontroller
public class tokencontroller {
    @resource
    private stringredistemplate stringredistemplate;
    // 生成防重令牌(前端调用接口前先获取)
    @getmapping("/api/token/get")
    public string getantiduplicatetoken() {
        // 生成uuid作为令牌
        string token = "anti_duplicate_token:" + uuid.randomuuid().tostring().replace("-", "");
        // 存入redis,过期时间5分钟(根据业务调整)
        stringredistemplate.opsforvalue().set(token, "1", 5, timeunit.minutes);
        return token;
    }
}
  1. 令牌验证切面(可复用方案 1 的注解,新增验证逻辑)
// 在antiduplicatesubmitaspect的around方法中新增token验证逻辑
private void validatetoken(httpservletrequest request) {
    string token = request.getheader("anti-duplicate-token");
    if (stringutils.isempty(token)) {
        throw new runtimeexception("缺少防重令牌,请先获取令牌!");
    }
    // 验证令牌是否存在,存在则删除(一次性使用)
    boolean exists = stringredistemplate.delete(token);
    if (exists == null || !exists) {
        throw new runtimeexception("令牌无效或已过期!");
    }
}
  1. 前端调用流程(伪代码)
// 1. 先获取令牌
fetch('/api/token/get').then(res => res.text()).then(token => {
    // 2. 带着令牌调用下单接口
    fetch('/api/order/create', {
        method: 'post',
        headers: {
            'content-type': 'application/json',
            'anti-duplicate-token': token // 令牌放在请求头
        },
        body: json.stringify({orderno: 'xxx', amount: 100})
    });
});

八年踩坑提示

  • 令牌过期时间要合理:太短(比如 1 分钟)用户操作慢会失效,太长(比如 30 分钟)占用 redis 内存;
  • 前端要处理令牌失效:如果调用业务接口时提示令牌过期,需重新获取令牌再重试;
  • 建议和方案 1 结合:令牌验证 + redis 限时锁,双重防护更稳妥。

适用场景:支付接口、退款接口等核心敏感接口

方案 3:基于本地缓存(caffeine)(单机高并发首选)

核心原理

如果是单机部署的应用,没必要用 redis,直接用本地缓存(caffeine)存储请求标识,效率更高(本地缓存响应时间微秒级)。

为什么用 caffeine?

caffeine 是 java 领域性能最好的本地缓存,支持过期时间、最大容量限制,比 hashmap + 定时任务更优雅,比 guava cache 性能高 5-10 倍。

实战代码

  1. 引入 caffeine 依赖(springboot 3.x)
<dependency>
    <groupid>com.github.ben-manes.caffeine</groupid>
    <artifactid>caffeine</artifactid>
    <version>3.1.8</version>
</dependency>
  1. 配置 caffeine 缓存
import com.github.benmanes.caffeine.cache.caffeine;
import org.springframework.cache.cachemanager;
import org.springframework.cache.caffeine.caffeinecachemanager;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import java.util.concurrent.timeunit;
@configuration
public class caffeineconfig {
    @bean
    public cachemanager antiduplicatecachemanager() {
        caffeinecachemanager cachemanager = new caffeinecachemanager();
        // 配置缓存:最大容量10万(防止内存溢出),过期时间1秒
        cachemanager.setcaffeine(caffeine.newbuilder()
                .maximumsize(100000)
                .expireafterwrite(1, timeunit.seconds));
        return cachemanager;
    }
}
  1. 改造切面(用本地缓存替代 redis)
import org.springframework.cache.cache;
import org.springframework.cache.cachemanager;
import org.springframework.stereotype.component;
// 在antiduplicatesubmitaspect中注入本地缓存管理器
@resource(name = "antiduplicatecachemanager")
private cachemanager cachemanager;
// 替换lua脚本逻辑,用本地缓存实现
private boolean checklocalcache(string requestkey) {
    cache cache = cachemanager.getcache("antiduplicatecache");
    if (cache == null) {
        throw new runtimeexception("本地缓存初始化失败!");
    }
    // 查缓存:存在则返回true(重复),不存在则存入缓存
    if (cache.get(requestkey) != null) {
        return true;
    }
    cache.put(requestkey, "1");
    return false;
}

八年踩坑提示

  • 必须设置最大容量:避免恶意请求导致缓存无限增长,引发 oom;
  • 仅适用于单机部署:多实例部署会出现缓存不一致,导致重复提交;
  • 过期时间要短:本地缓存不支持分布式过期,太长会占用内存。

适用场景:单机部署、高并发读少写多的接口(比如查询 + 提交类接口)

方案 4:基于数据库唯一索引(兜底方案,最可靠)

核心原理

无论前端、缓存层防护得多好,数据库层都要加 “最后一道防线”—— 给核心业务字段建唯一索引(比如订单号、用户 id + 商品 id),即使重复提交,数据库也会抛出唯一约束异常,避免数据错乱。

为什么是兜底?

缓存可能失效,令牌可能被绕过,但数据库唯一索引是 “物理防护”,除非删索引,否则绝对不会出现重复数据 —— 八年开发的底线:核心业务必须加唯一索引!

实战代码

  1. 数据库表设计(以订单表为例)
create table `t_order` (
  `id` bigint not null auto_increment,
  `order_no` varchar(64) not null comment '订单号(唯一)',
  `user_id` bigint not null comment '用户id',
  `product_id` bigint not null comment '商品id',
  `amount` decimal(10,2) not null comment '金额',
  primary key (`id`),
  -- 唯一索引:订单号唯一(防止重复下单)
  unique key `uk_order_no` (`order_no`),
  -- 联合唯一索引:同一用户不能同时买同一商品(根据业务需求)
  unique key `uk_user_product` (`user_id`,`product_id`)
) engine=innodb default charset=utf8mb4 comment='订单表';
  1. 业务代码处理唯一约束异常
import org.springframework.dao.duplicatekeyexception;
import org.springframework.web.bind.annotation.exceptionhandler;
import org.springframework.web.bind.annotation.restcontrolleradvice;
@restcontrolleradvice
public class globalexceptionhandler {
    // 捕获数据库唯一约束异常,返回友好提示
    @exceptionhandler(duplicatekeyexception.class)
    public string handleduplicatekeyexception(duplicatekeyexception e) {
        log.error("重复提交导致唯一约束冲突:", e);
        return "操作失败,请勿重复提交!";
    }
}

八年踩坑提示

  • 唯一索引要贴合业务:别盲目建唯一索引,比如 “用户 id + 商品 id” 适合 “限购一件” 的场景,“订单号” 适合所有订单唯一的场景;
  • 避免过度建索引:索引会影响插入性能,核心字段才需要;
  • 异常信息要脱敏:别把数据库表结构、字段名暴露给前端。

适用场景:所有核心业务接口(支付、下单、退款),作为兜底方案

方案 5:基于 aop + 自定义注解(优雅封装,复用性强)

核心原理

把方案 1-4 的逻辑封装成通用注解,业务接口只需加注解即可实现防抖,无需写重复代码 —— 这是八年开发的 “偷懒技巧”:一次封装,处处复用。

进阶封装:支持多场景切换

// 增强antiduplicatesubmit注解,支持选择防抖方式
public @interface antiduplicatesubmit {
    // 防抖方式:redis/local_cache/token
    mode mode() default mode.redis;
    long timeout() default 1;
    timeunit unit() default timeunit.seconds;
    string message() default "操作过于频繁,请稍后再试!";
    enum mode {
        redis, local_cache, token
    }
}

改造切面:根据注解模式选择防抖方案

@around("@annotation(antiduplicatesubmit)")
public object around(proceedingjoinpoint joinpoint, antiduplicatesubmit antiduplicatesubmit) throws throwable {
    string requestkey = generaterequestkey(joinpoint, antiduplicatesubmit.method());
    antiduplicatesubmit.mode mode = antiduplicatesubmit.mode();
    // 根据模式选择不同方案
    if (mode == antiduplicatesubmit.mode.redis) {
        // redis+lua方案
        long result = stringredistemplate.execute(antiduplicatescript, collections.singletonlist(requestkey), string.valueof(timeout));
        if (result != null && result == 1) {
            throw new runtimeexception(antiduplicatesubmit.message());
        }
    } else if (mode == antiduplicatesubmit.mode.local_cache) {
        // 本地缓存方案
        if (checklocalcache(requestkey)) {
            throw new runtimeexception(antiduplicatesubmit.message());
        }
    } else if (mode == antiduplicatesubmit.mode.token) {
        // token方案
        validatetoken(request);
    }
    return joinpoint.proceed();
}

接口使用示例(按需选择模式)

// 支付接口:用token模式(最安全)
@antiduplicatesubmit(mode = antiduplicatesubmit.mode.token, message = "支付请求已提交,请勿重复操作!")
@postmapping("/api/pay")
public string pay(@requestbody paydto paydto) { ... }
// 下单接口:用redis模式(分布式高并发)
@antiduplicatesubmit(mode = antiduplicatesubmit.mode.redis, timeout = 2)
@postmapping("/api/order/create")
public string createorder(@requestbody orderdto orderdto) { ... }
// 评论接口:用local_cache模式(单机部署)
@antiduplicatesubmit(mode = antiduplicatesubmit.mode.local_cache)
@postmapping("/api/comment/add")
public string addcomment(@requestbody commentdto commentdto) { ... }

适用场景:全场景复用,大型项目推荐(减少重复开发)

三、八年踩坑总结:3 个致命错误别犯!

  1. 只做前端防抖,不做后端防护:前端按钮禁用能防 “手抖”,但防不住爬虫、postman 直接调用 —— 后端必须加防护;
  2. 忽略幂等性设计:防抖是 “阻止调用”,防重是 “保证结果一致”,比如支付接口,即使防抖失效,重复调用也不能扣两次钱;
  3. redis 过期时间设置不合理:太短导致正常请求被误判,太长导致用户无法重试 —— 建议根据业务调整,一般 1-5 秒。

四、选型指南:一张表选对方案

方案适用场景优点缺点
redis+lua分布式、高并发性能高、支持分布式需部署 redis
token 令牌敏感接口(支付 / 退款)最安全、防恶意刷接口前后端联动成本高
本地缓存(caffeine)单机部署、高并发响应快、无网络开销不支持分布式
数据库唯一索引核心业务兜底最可靠、物理防护影响插入性能
aop + 自定义注解大型项目、多场景复用性强、优雅简洁需提前封装

一句话口诀:分布式用 redis,敏感接口用 token,单机用 caffeine,核心业务加索引。

五、总结

八年开发经验告诉我:接口防抖不是 “炫技”,而是 “底线思维”。一套完善的防抖方案,应该是 “前端按钮禁用 + 后端多重防护 + 数据库兜底” 的组合拳 —— 前端防普通用户,后端防恶意攻击,数据库防所有漏网之鱼。

本文的 5 种方案,从单机到分布式,从临时防护到长期复用,覆盖了所有场景,代码都经过实际项目验证,可直接复制使用。如果你的项目还在被重复提交困扰,不妨根据业务场景选择合适的方案,早日实现 “接口防抖自由”。

到此这篇关于springboot接口防抖实战之防重复提交的5种高级方案的文章就介绍到这了,更多相关springboot接口防重复提交内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com