哈喽,大家好,我是了不起。

无论调用接口的次数为一次或多次,接口的幂等性保证对同一资源的操作只会产生同样的结果。多次重复调用相同的接口请求应该具有与单次请求相同的结果,不能引起不一致性或副作用的发生。

今天我们利用人工智能,创建了一个定制注解,以防止接口在30秒内被多次请求,并用Redis作为缓存。

提问

话不多说,直接提问:

今天用AI搞一个防止接口重复提交注解-LMLPHP

等待数分钟后。。。

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

今天用AI搞一个防止接口重复提交注解-LMLPHP

2.然后创建拦截器

今天用AI搞一个防止接口重复提交注解-LMLPHP

这里我们贴出拦截器的核心代码:

@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搞一个防止接口重复提交注解-LMLPHP

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

今天用AI搞一个防止接口重复提交注解-LMLPHP


上面就是最关键的代码了。

接入Redis

下面我们接入Redis。最精简的配置版本

spring:data:redis:host: 127.0.0.1 port: 6379
登录后复制

接口使用注解

@RestControllerpublic class RepeatTestController {@RepeatSubmit@GetMapping("/hello/mono1")public Mono<String> mono(){return Mono.just("Hello Mono -Java North");}@RepeatSubmit@PostMapping ("/hello/mono1")public Mono<String> mono1(@RequestBody User user){return Mono.just("Hello Mono -Java North-"+user.getName());}}
登录后复制

本地起一个Redis,然后启动本地的SpringBoot项目进行测试,

今天用AI搞一个防止接口重复提交注解-LMLPHP

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

今天用AI搞一个防止接口重复提交注解-LMLPHP

Redis中缓存的KEY如下:

今天用AI搞一个防止接口重复提交注解-LMLPHP

相关代码在文章末尾,需要的话可以白嫖哈!

接口幂等性解决方案

下面问一下接口幂等性解决方案,

今天用AI搞一个防止接口重复提交注解-LMLPHP

关于这个回答,大家觉得怎么样?

相关代码链接,欢迎来嫖:

https://www.php.cn/link/94c0915ab3bcbc61c1c61624dd6d7cd5

以上就是今天用AI搞一个防止接口重复提交注解的详细内容,更多请关注Work网其它相关文章!

09-12 13:32