Spring boot接口防抖

防抖是一种减少高频触发的机制,在一定时间内,连续的多次操作只会触发一次。后端防抖主要用于避免短时间内的重复请求。

其主要目的是防止在短时间内因多次触发相同事件而导致不必要的处理开销,比如频繁的数据库查询、API调用等。接口防抖通常用于处理用户输入、按钮点击等场景,以提高系统的性能和响应速度。

第一步:自定义注解 @AntiShake

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AntiShake {
    long value() default 1000L; // 默认1秒内不允许重复请求
}

第二步:利用AOP实现防抖




import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicLong;

@Aspect
@Component
public class AntiShakeAspect {

    // 使用 AtomicLong 来确保线程安全
    private AtomicLong lastInvokeTime = new AtomicLong(0L);

    @Around("@annotation(antiShake)")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint, AntiShake antiShake) throws Throwable {
        // 获取当前时间
        long currentTime = System.currentTimeMillis();

        // 获取最后一次调用的时间
        long previousTime = lastInvokeTime.get();

        // 检查是否超过了防抖动阈值
        if (currentTime - previousTime < antiShake.value()) {
            // 请求过于频繁,返回提示信息
            return "请求过于频繁,请稍后再试。";
        }

        // 允许方法调用
        Object result = joinPoint.proceed();

        // 在方法成功执行后更新最后一次调用的时间
        lastInvokeTime.set(currentTime);

        return result;
    }
}

第三步: 注册防抖切面

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;


@Configuration
@EnableAspectJAutoProxy
public class AntiShakeAutoConfiguration {
    @Bean
    public AntiShakeAspect customAntiShakeAspect() {
        return new AntiShakeAspect();
    }
}

最后:测试

@RestController
public class TestController {
    @GetMapping("/query")
    @AntiShake(value = 1000)
    public String test() {
        return "hello world";
    }
}

最终效果:

对您有帮助的话辛苦您关注一下微信公众号哦!谢谢

清宁时光秀

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

晴天飛 雪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值