在现代 Web 应用中,前端与后端的交互频繁而复杂,用户的操作如按钮点击、表单提交等,都会引发向后端发送请求。虽然这些请求中的多数是有意义的,但一些场景下,用户的误操作或网络波动可能导致同一请求在短时间内被重复触发。这种重复请求不仅会增加服务器的负担,消耗宝贵的资源,还可能引发数据不一致性的问题。因此,如何有效地防止接口被频繁调用,成为了开发者必须解决的问题。
接口防抖是一种常见的优化手段,通过延迟请求的处理或限制请求的频率,来确保在一定时间内只执行一次操作,从而减少服务器负担。本文将深入探讨几种常见的接口防抖策略及其在 Spring Boot 3.3 项目中的实现,并展示如何通过配置来灵活选择不同的防抖方案。此外,还将介绍如何在前端使用 Jquery 实现按钮的防抖点击,从而进一步优化用户体验。
什么是接口防抖
接口防抖(Debounce)是一种前后端结合的技术手段,主要用于防止在短时间内多次触发同一操作。通常情况下,用户可能会因为网络延迟、误点击等原因在短时间内多次发送相同的请求,如果不加以控制,这些请求会同时传递到服务器,导致服务器处理多次同一业务逻辑,从而造成资源浪费甚至系统崩溃。
防抖技术可以通过延迟处理或限制频率,确保在指定时间内同一操作只被执行一次。例如,用户在点击按钮时,如果短时间内多次点击,只有第一个请求会被处理,后续请求将被忽略。这种机制不仅可以优化服务器性能,还能提升用户体验。
运行效果:
图片
图片
若想获取项目完整代码以及其他文章的项目源码,且在代码编写时遇到问题需要咨询交流,欢迎加入下方的知识星球。
项目基础配置
pom.xml 配置
首先,在 pom.xml 中配置 Spring Boot、Thymeleaf、Bootstrap,以及其他相关依赖:
<?xml versinotallow="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.icoderoad</groupId>
<artifactId>debounce</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>debounce</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml 配置
在 application.yml 中配置接口防抖策略的选择:
server:
port: 8080
spring:
debounce:
strategy: time-window # 可选值:time-window, token-bucket, sliding-window
time-window:
duration: 1000 # 时间窗口长度(毫秒)
token-bucket:
capacity: 10 # 令牌桶容量
refill-rate: 1 # 令牌补充速率(每秒)
sliding-window:
size: 5 # 滑动窗口大小
interval: 1000 # 时间间隔(毫秒)
接口防抖策略实现
定义 DebounceStrategy 接口
package com.icoderoad.debounce.strategy;
public interface DebounceStrategy {
/**
* 判断当前请求是否应该被处理
*
* @param key 唯一标识(如用户ID、IP等)
* @return 如果应该处理请求,返回true;否则返回false
*/
boolean shouldProceed(String key);
}
时间窗口防抖(time-window)
时间窗口防抖策略(Time Window Debounce)是最简单的一种防抖机制,它允许在一个固定的时间窗口内只执行一次操作。例如,在设置了 1 秒的时间窗口后,无论用户在这一秒内点击多少次按钮,系统只会响应第一次点击,其余的点击将被忽略。时间窗口策略适用于那些短时间内不希望重复操作的场景。
时间窗口策略实现
首先,实现时间窗口策略:
package com.icoderoad.debounce.strategy;
import java.util.concurrent.ConcurrentHashMap;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component("timeWindowStrategy")
public class TimeWindowStrategy implements DebounceStrategy {
private final long durationMillis;
private final ConcurrentHashMap<String, Long> requestTimes = new ConcurrentHashMap<>();
public TimeWindowStrategy(@Value("${spring.debounce.time-window.duration}") long durationMillis) {
this.durationMillis = durationMillis;
}
@Override
public boolean shouldProceed(String key) {
long currentTime = System.currentTimeMillis();
Long lastRequestTime = requestTimes.put(key, currentTime);
if (lastRequestTime == null || currentTime - lastRequestTime >= durationMillis) {
return true;
} else {
return false;
}
}
}
令牌桶防抖(token-bucket)
令牌桶防抖策略(Token Bucket Debounce)通过维护一个令牌桶,每次请求需要消耗一个令牌。当令牌桶为空时,请求将被拒绝或延迟处理。令牌会以固定的速率被重新生成,确保在长时间内的请求可以被平稳处理。令牌桶策略适用于那些需要控制请求速率的场景,如 API 限流。
令牌桶策略实现
package com.icoderoad.debounce.strategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
@Component("tokenBucketStrategy")
public class TokenBucketStrategy implements DebounceStrategy {
private final int capacity;
private final int refillRate;
private final ConcurrentHashMap<String, Semaphore> tokenBuckets = new ConcurrentHashMap<>();
public TokenBucketStrategy(
@Value("${spring.debounce.token-bucket.capacity}") int capacity,
@Value("${spring.debounce.token-bucket.refill-rate}") int refillRate) {
this.capacity = capacity;
this.refillRate = refillRate;
startRefillTask();
}
@Override
public boolean shouldProceed(String key) {
Semaphore semaphore = tokenBuckets.computeIfAbsent(key, k -> new Semaphore(capacity));
return semaphore.tryAcquire();
}
private void startRefillTask() {
new Thread(() -> {
while (true) {
try {
Thread.sleep(1000 / refillRate);
tokenBuckets.forEach((key, semaphore) -> semaphore.release(1));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}).start();
}
}
滑动窗口防抖(sliding-window)
滑动窗口防抖策略(Sliding Window Debounce)通过在一个固定的时间窗口内统计请求次数,并将其滑动以覆盖整个时间区间。只允许在这个窗口内的一定次数的请求通过。滑动窗口策略适用于需要在一段时间内精确控制请求次数的场景。
滑动窗口策略实现
package com.icoderoad.debounce.strategy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.LinkedBlockingQueue;
@Component("slidingWindowStrategy")
public class SlidingWindowStrategy implements DebounceStrategy {
private final int maxSize;
private final long intervalMillis;
private final ConcurrentHashMap<String, LinkedBlockingQueue<Long>> requestTimestamps = new ConcurrentHashMap<>();
public SlidingWindowStrategy(
@Value("${spring.debounce.sliding-window.size}") int maxSize,
@Value("${spring.debounce.sliding-window.interval}") long intervalMillis) {
this.maxSize = maxSize;
this.intervalMillis = intervalMillis;
}
@Override
public boolean shouldProceed(String key) {
long currentTime = System.currentTimeMillis();
LinkedBlockingQueue<Long> timestamps = requestTimestamps.computeIfAbsent(key, k -> new LinkedBlockingQueue<>());
synchronized (timestamps) {
while (!timestamps.isEmpty() && currentTime - timestamps.peek() > intervalMillis) {
timestamps.poll();
}
if (timestamps.size() < maxSize) {
timestamps.offer(currentTime);
return true;
} else {
return false;
}
}
}
}
策略选择器
package com.icoderoad.debounce.strategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class DebounceStrategySelector {
@Value("${spring.debounce.strategy}")
private String strategy;
private final TimeWindowStrategy timeWindowStrategy;
private final TokenBucketStrategy tokenBucketStrategy;
private final SlidingWindowStrategy slidingWindowStrategy;
@Autowired
public DebounceStrategySelector(
TimeWindowStrategy timeWindowStrategy,
TokenBucketStrategy tokenBucketStrategy,
SlidingWindowStrategy slidingWindowStrategy) {
this.timeWindowStrategy = timeWindowStrategy;
this.tokenBucketStrategy = tokenBucketStrategy;
this.slidingWindowStrategy = slidingWindowStrategy;
}
public DebounceStrategy select() {
switch (strategy) {
case "token-bucket":
return tokenBucketStrategy;
case "sliding-window":
return slidingWindowStrategy;
case "time-window":
default:
return timeWindowStrategy;
}
}
}
自定义注解
package com.icoderoad.debounce.aspect;
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 Debounce {
String key() default "";
long duration() default 1000;
}
AOP 实现
将防抖策略的选择集成到 AOP 中:
package com.icoderoad.debounce.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.icoderoad.debounce.strategy.DebounceStrategy;
import com.icoderoad.debounce.strategy.DebounceStrategySelector;
import com.icoderoad.debounce.strategy.SlidingWindowStrategy;
import com.icoderoad.debounce.strategy.TimeWindowStrategy;
import com.icoderoad.debounce.strategy.TokenBucketStrategy;
@Aspect
@Component
public class DebounceAspect {
private final DebounceStrategySelector strategySelector;
@Autowired
public DebounceAspect(DebounceStrategySelector strategySelector) {
this.strategySelector = strategySelector;
}
@Around("@annotation(debounce)")
public Object around(ProceedingJoinPoint joinPoint, Debounce debounce) throws Throwable {
DebounceStrategy strategy = strategySelector.select();
String key = debounce.key();
if (strategy instanceof TimeWindowStrategy) {
if (((TimeWindowStrategy) strategy).shouldProceed(key)) {
return joinPoint.proceed();
}
} else if (strategy instanceof TokenBucketStrategy) {
if (((TokenBucketStrategy) strategy).shouldProceed(key)) {
return joinPoint.proceed();
}
} else if (strategy instanceof SlidingWindowStrategy) {
if (((SlidingWindowStrategy) strategy).shouldProceed(key)) {
return joinPoint.proceed();
}
}
throw new RuntimeException("请求频率过高,请稍后再试。");
}
}
自定义异常类
首先,可以定义一个自定义异常类 TooManyRequestsException:
package com.icoderoad.debounce.exception;
public class TooManyRequestsException extends RuntimeException {
public TooManyRequestsException(String message) {
super(message);
}
}
创建错误响应体
定义一个简单的 ErrorResponse 类,用于返回错误信息:
package com.icoderoad.debounce.exception;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class ErrorResponse {
private String message;
}
创建自定义异常处理
使用 @ControllerAdvice 和 @ExceptionHandler 处理 TooManyRequestsException 异常,并返回自定义的响应体和状态码:
package com.icoderoad.debounce.handler;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.icoderoad.debounce.exception.ErrorResponse;
import com.icoderoad.debounce.exception.TooManyRequestsException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(TooManyRequestsException.class)
public ResponseEntity<Object> handleTooManyRequestsException(TooManyRequestsException ex) {
// 返回 429 状态码和自定义错误信息
return ResponseEntity
.status(HttpStatus.TOO_MANY_REQUESTS)
.body(new ErrorResponse("请求频率过高,请稍后再试!"));
}
}
接口控制器实现 DebounceController
package com.icoderoad.debounce.controller;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import com.icoderoad.debounce.aspect.Debounce;
@RestController
public class DebounceController {
@Debounce(key = "debounceTest")
@GetMapping("/api/debounce-test")
public ResponseEntity<String> debounceTest() {
return ResponseEntity.ok("请求成功!");
}
}
视图控制器
package com.icoderoad.debounce.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class IndexController {
@GetMapping("/")
public String index() {
return "index";
}
}
前端实现
前端使用 Bootstrap 实现一个简单的按钮触发接口调用的页面,并展示防抖效果。
在src/main/resources/templates目录下创建文件 index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>接口防抖测试</title>
<!-- 使用HTTP协议引入Bootstrap和jQuery -->
<link rel="stylesheet" href="http://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="http://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="container mt-5">
<h1 class="mb-4">接口防抖测试</h1>
<!-- 按钮,点击后触发请求 -->
<button id="debounceButton" class="btn btn-primary btn-lg">触发请求</button>
<!-- 用于显示响应结果的div -->
<div id="responseMessage" class="mt-3 alert" style="display:none;"></div>
</div>
<!-- 引入Bootstrap的JS文件 -->
<script src="http://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script>
/**
* 防抖函数
* @param func 需要防抖的函数
* @param delay 延迟时间,单位毫秒
* @returns {Function}
*/
function debounce(func, delay) {
let timer = null;
return function(...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, delay);
};
}
$(document).ready(function () {
const $button = $('#debounceButton');
const $responseDiv = $('#responseMessage');
/**
* 发送请求的函数
*/
function sendRequest() {
$.ajax({
url: '/api/test',
method: 'GET',
success: function(data) {
$responseDiv
.removeClass('alert-danger')
.addClass('alert-success')
.text(data)
.show();
},
error: function(xhr) {
$responseDiv
.removeClass('alert-success')
.addClass('alert-danger')
.text('请求过于频繁,请稍后再试!')
.show();
}
});
}
// 使用防抖函数包装sendRequest,防止频繁点击
const debouncedSendRequest = debounce(sendRequest, 500); // 500毫秒内只执行一次
$button.on('click', debouncedSendRequest);
});
</script>
</body>
</html>
总结
在本文中,我们深入探讨了几种常见的接口防抖策略——时间窗口、令牌桶、滑动窗口,并展示了如何在 Spring Boot 3.3 项目中实现这些策略。通过配置文件的灵活选择,可以在不同场景下使用不同的防抖策略,从而优化系统的性能和稳定性。此外,我们还介绍了如何在前端页面中使用 Jquery 实现按钮的防抖点击,进一步防止用户重复操作。通过这些防抖手段,可以有效地降低系统的负载,提高用户体验,避免潜在的系统风险。