springboot 基于google 缓存,实现防重复提交

在Spring Boot应用中,可以使用Google Guava缓存来实现防重复提交功能。Guava提供了强大的缓存机制,可以方便地实现对请求的去重处理。。

1. 添加依赖

首先,在你的pom.xml文件中添加Guava的依赖:

复制代码
<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>
复制代码

2. 创建缓存配置类

创建一个配置类来初始化Guava缓存:

复制代码
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.TimeUnit;

@Configuration
public class CacheConfig {

    @Bean
    public Cache<String, String> requestCache() {
        return CacheBuilder.newBuilder()
                .expireAfterWrite(5, TimeUnit.MINUTES) // 设置缓存过期时间
                .build();
    }
}
复制代码

3. 创建防重复提交拦截器

接下来,创建一个拦截器来检查请求是否重复:

复制代码
import com.google.common.cache.Cache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class DuplicateSubmissionInterceptor implements HandlerInterceptor {

    @Autowired
    private Cache<String, String> requestCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String key = generateKey(request);
        if (key != null && requestCache.getIfPresent(key) != null) {
            response.setStatus(HttpServletResponse.SC_CONFLICT); // 409 Conflict
            return false;
        } else {
            requestCache.put(key, "");
            return true;
        }
    }

    private String generateKey(HttpServletRequest request) {
        // 根据请求生成唯一键,例如可以根据URL和参数生成MD5值
        String url = request.getRequestURI();
        String queryString = request.getQueryString();
        return url + (queryString != null ? "?" + queryString : "");
    }
}
复制代码

4. 注册拦截器

最后,将拦截器注册到Spring MVC中:

复制代码
mport org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private DuplicateSubmissionInterceptor duplicateSubmissionInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(duplicateSubmissionInterceptor).addPathPatterns("/**"); // 对所有请求进行拦截
    }
}
复制代码

总结

通过以上步骤,已经成功实现了一个基于Guava缓存的防重复提交功能。利用Guava缓存的高效性和简洁性,能够有效地防止短时间内的重复请求。你可以根据实际需求调整缓存的过期时间和生成唯一键的逻辑。

推荐阅读

nginx代理udp协议

springboot 自定义注解实现redis 秒级 缓存

springboot rocketmq 一秒拉取一次消息,批量消费消息

java hashmap 面试题

springboot与tio-websocket自定义集群模式

相关推荐
江湖十年32 分钟前
Go 虚荣域名详解:我用 go get -x 抓了个包,终于看清了 Go 工具链“对暗号”的全过程
后端·面试·go
Lost of 程序猿34 分钟前
船岸数据同步链路实战:SendFlag、单调版本号与断网三天后的续传
后端·c#·asp.net
卷无止境37 分钟前
大模型如何调用工具,一次讲清背后的技术门道
后端·python
90后的晨仔44 分钟前
Python 进阶:海象运算符与模式匹配,让你的代码更优雅!
后端
卷无止境7 小时前
智能体开发环境ADE浅析,编程工具的下一次范式跃迁
后端·python
码事漫谈10 小时前
DeepSeek 这波操作很凶
后端
mengzhi啊10 小时前
缓存类CacheDataManager把临时数据存入json。做成插件·
qt·缓存·json
Bs_MoneyMagnet11 小时前
基于springboot+vue的医疗健康便民服务平台的设计与实现 源码+文档
java·vue.js·spring boot·后端·spring
子兮曰12 小时前
Bun v1.4.1 深度解析:从 Zig 到 Rust,一场 11 天、64 个 AI 代理的语言迁徙
前端·后端·bun
loser.with.m13 小时前
【AgentScope 2.0】05-从数据库配置到可运行 Agent:十个 Builder 开关怎么把一行 JSON 变成 HarnessAgent
人工智能·spring boot·ai