在Spring Boot中结合Redis来防止重复提交,通常的做法是利用Redis的原子性操作来实现。以下是一个简单的示例,展示如何使用Redis来防止用户在短时间内重复提交表单。
1. 添加依赖
首先,确保你的Spring Boot项目中已经添加了Spring Data Redis和Redis客户端的依赖。在pom.xml
中添加如下依赖:
<dependencies>
<!-- Spring Boot Redis starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- Redis客户端 Lettuce -->
<dependency>
<groupId>io.lettuce.core</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
</dependencies>
2. 配置Redis
在application.properties
或application.yml
中配置Redis连接信息:
# application.properties
spring.redis.host=localhost
spring.redis.port=6379
3. 创建Redis配置类
创建一个配置类来配置Redis模板:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
}
4. 创建防止重复提交的服务
创建一个服务类,用于检查和设置Redis中的锁:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
@Service
public class RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
public boolean trySetIfAbsent(String key, String value, long timeout, TimeUnit unit) {
Boolean result = redisTemplate.opsForValue().setIfAbsent(key, value, timeout, unit);
return result != null && result;
}
public void delete(String key) {
redisTemplate.delete(key);
}
}
5. 使用服务防止重复提交
在你的控制器或业务逻辑中使用这个服务来防止重复提交:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SubmissionController {
@Autowired
private RedisService redisService;
@PostMapping("/submit")
public String submitForm(String userId, String data) {
String key = "submit:" + userId;
String value = "locked";
long timeout = 5; // 5秒内不允许重复提交
if (redisService.trySetIfAbsent(key, value, timeout, TimeUnit.SECONDS)) {
// 处理提交逻辑
return "提交成功";
} else {
return "请勿重复提交";
}
}
}