Spring Boot防重复提交

 

网速比较慢的情况下,用户提交表单后,发现服务器半天都没有响应,用户极有可能会以为是自己没有提交表单,就会再点击提交按钮重复提交表单。我们在开发中必须防止表单重复提交,否则很有可能会生成非法数据。本文介绍一种非分布式服务后台防重复提交的一种实现方式,虽然在实际工作中,单点部署的服务已经很少了,但是我还是决定单独介绍一下,本文实现方提交的方式就是在服务后台通过缓存实现一个本地锁,获取锁的过程就是从缓存中获取数据的过程,如果缓存中存在数据,则表示获取锁失败,缓存中不存在数据,则讲缓存写入成功获取锁。然后通过切面拦截的方式,判断是否重复提交。

1. 项目结构
|   pom.xml
|   springboot-16-repeat-submit.iml
|
+---src
|   +---main
|   |   +---java
|   |   |   \---com
|   |   |       \---zhuoli
|   |   |           \---service
|   |   |               \---springboot
|   |   |                   \---repeat
|   |   |                       \---submit
|   |   |                           |   AntiRepeatedSubmitApplicationContext.java
|   |   |                           |
|   |   |                           +---annotation
|   |   |                           |       Submit.java
|   |   |                           |
|   |   |                           +---aop
|   |   |                           |       SubmitAspect.java
|   |   |                           |
|   |   |                           +---common
|   |   |                           |       User.java
|   |   |                           |
|   |   |                           +---controller
|   |   |                           |       UserController.java
|   |   |                           |
|   |   |                           \---service
|   |   |                               |   UserControllerService.java
|   |   |                               |
|   |   |                               \---impl
|   |   |                                       UserControllerServiceImpl.java
|   |   |
|   |   \---resources
|   \---test
|       \---java
其中Submit.java为自定义注解,通过指定注解可以设置接口本地锁的key;SubmitAspect.java为切面,拦截自定义注解注解,获取本地锁key获取锁,如果获取锁失败,表示为重复提交。

2. pom.xml
<?xml version="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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.zhuoli.service</groupId>
    <artifactId>springboot-16-repeat-submit</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <!-- Spring Boot 启动父依赖 -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.3.RELEASE</version>
    </parent>
 
    <dependencies>
        <!-- Exclude Spring Boot's Default Logging -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
 
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>
 
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>21.0</version>
        </dependency>
 
    </dependencies>
 
</project>
3. 核心代码介绍
3.1 自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface Submit {
 
    String prefix() default "prefix:";
}
prefix为本地锁的key的前缀。

3.2 拦截切面
@Aspect
@Configuration
public class SubmitAspect {
    private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
            // 最大缓存 100 个
            .maximumSize(100)
            // 设置缓存过期时间为5S
            .expireAfterWrite(5, TimeUnit.SECONDS)
            .build();
 
    @Around("execution(public * *(..)) && @annotation(com.zhuoli.service.springboot.repeat.submit.annotation.Submit)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        Submit submit = method.getAnnotation(Submit.class);
        String key = getCacheKey(submit, pjp.getArgs());
        if (!StringUtils.isEmpty(key)) {
            if (CACHES.getIfPresent(key) != null) {
                throw new RuntimeException("请勿重复请求");
            }
            // 如果是第一次请求,就将key存入缓存中
            CACHES.put(key, key);
        }
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException("服务器异常");
        } finally {
            //如果演示的话需要注释该代码,手动将缓存清除,实际应该放开
            //CACHES.invalidate(key);
        }
    }
 
    /**
     * Cache key生成策略,这里可以自定义实现,比如再Submit注解中添加需要从request中获取字段名称,在此方法中通过反射获取,拼接为最终的Cache key
     * 本方法Cache key使用最简单的策略:prefix + request参数的toString,这里只做展示使用,一般不会使用这种策略,一是会导致cache key过长,浪费存储空间,
     * 二是,如果请求参数没有实现toString方法,对于相同的请求参数,依然会被认为是两个不同的请求
     */
    private String getCacheKey(Submit submit, Object[] args) {
        String prefix = submit.prefix();
        return prefix + args[0];
    }
}
内容很简单,就是通过key获取缓存,写缓存的过程,不多讲解了。

3.3 自定义注解使用
@RestController
@RequestMapping("/user")
@AllArgsConstructor
public class UserController {
 
    private UserControllerService userControllerService;
 
    @Submit
    @RequestMapping(value = "/get_user", method = RequestMethod.POST)
    public ResponseEntity getUserById(@RequestParam Long id){
        return ResponseEntity.status(HttpStatus.OK).body(userControllerService.getUserById(id));
    }
}
每次获取的时候,本地锁的key为getCacheKey方法生成的字符串,策略为"prefix:" + id。所以5s内对于同一个id的请求, 肯定会被拦截掉。

4. 测试

接口请求成功,5S内重新请求

说明本地锁放重复提交生效了
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值