哈喽,大家好,我是了不起。
无论调用接口的次数为一次或多次,接口的幂等性保证对同一资源的操作只会产生同样的结果。多次重复调用相同的接口请求应该具有与单次请求相同的结果,不能引起不一致性或副作用的发生。
今天我们利用人工智能,创建了一个定制注解,以防止接口在30秒内被多次请求,并用Redis作为缓存。
提问
话不多说,直接提问:
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

等待数分钟后。。。
1.创建自定义注解 其中包括接口保护时长,开启防止重复提交保护等。

2.然后创建拦截器

这里我们贴出拦截器的核心代码:
@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {if (handler instanceof HandlerMethod) {HandlerMethod handlerMethod = (HandlerMethod) handler;RepeatSubmit annotation = handlerMethod.getMethodAnnotation(RepeatSubmit.class);if (annotation != null && annotation.enable()) {String key = buildKey(request);if (StringUtils.hasText(redisTemplate.opsForValue().get(key))) {response.getWriter().write("repeat request, please try again later!");return false;} else {redisTemplate.opsForValue().set(key, Arrays.toString(request.getInputStream().readAllBytes()), annotation.timeout(), TimeUnit.SECONDS);}}}return true;} //创建redis 缓存keyprivate String buildKey(HttpServletRequest request) throws IOException, NoSuchAlgorithmException {String key = useRequestMD5 ? hashRequest(request) : request.getRequestURI();return "repeat-submit:" + key;} //对请求做hash运算private String hashRequest(HttpServletRequest request) throws IOException, NoSuchAlgorithmException {byte[] hashBytes = MessageDigest.getInstance("MD5").digest(request.getInputStream().readAllBytes());StringBuilder sb = new StringBuilder();for (byte b : hashBytes) {sb.append(String.format("%02x", b));}return sb.toString();}
3.注册拦截器

最后给出的解释与使用方法。

上面就是最关键的代码了。
降重鸟
要想效果好,就用降重鸟。AI改写智能降低AIGC率和重复率。
113 查看详情
接入Redis
下面我们接入Redis。最精简的配置版本
spring:data:redis:host: 127.0.0.1 port: 6379
接口使用注解
@RestControllerpublic class RepeatTestController {@RepeatSubmit@GetMapping("/hello/mono1")public Mono mono(){return Mono.just("Hello Mono -Java North");}@RepeatSubmit@PostMapping ("/hello/mono1")public Mono mono1(@RequestBody User user){return Mono.just("Hello Mono -Java North-"+user.getName());}}
本地起一个Redis,然后启动本地的SpringBoot项目进行测试,

本地接口测试:30秒内重复请求会需要直接被拦截

Redis中缓存的KEY如下:

相关代码在文章末尾,需要的话可以白嫖哈!
接口幂等性解决方案
下面问一下接口幂等性解决方案,

关于这个回答,大家觉得怎么样?
相关代码链接,欢迎来嫖:
https://www.php.cn/link/94c0915ab3bcbc61c1c61624dd6d7cd5
以上就是今天用AI搞一个防止接口重复提交注解的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/532531.html
微信扫一扫
支付宝扫一扫