模拟防止重复提交

发布于:2024-07-11 ⋅ 阅读:(15) ⋅ 点赞:(0)

 gitee地址(需要自取)AopProxy重复提交: 防止重复提交 (gitee.com)

@RestController
public class SubmissionController {

    @Autowired
    private SubmissionService submissionService;

    private static Jedis jedis = new Jedis("localhost",6379);
    private String lock = "lock";
    private String lockValue = "locked";
    private int gqsj = 5;
    private String ok = "OK";

    @PostMapping("/submit")
    public void handleSubmitForm(@RequestParam String name, @RequestParam int age) {
        SubmissionService submissionServiceProxy = (SubmissionService) Proxy.newProxyInstance(submissionService.getClass().getClassLoader(), new Class[]{SubmissionService.class}, (proxy, method, args) -> {
            SetParams params = new SetParams();
            params.nx().ex(gqsj);
            String res = jedis.set(lock, lockValue,params);
            if (ok.equals(res)){
                Object invoke = method.invoke(submissionService,name,age);
                System.out.println("提交成功");
                return invoke;
            }else {
                System.out.println("不允许重复提交");
                return null;
            }
        });

        submissionServiceProxy.insert(name, age);


//      存疑?第一天晚上return null后汇报一个空指针错误,奇怪的是第二天不报错了
//      希望懂得大佬给小弟支个招

//        try{
//            submissionServiceProxy.insert(name, age);
//        }catch (NullPointerException e){
//            System.out.println("禁止重复提交");
//        }
    }
}

思路就是使用代理来执行方法,使用aop的思想对其进行切片,在执行方法前加一个分布式锁,这里分布式锁采用的是redis.nx,并加上一个过期时间防止死锁。整体只做了一个简单模拟,写的比较简单,有错误或不足的地方,还请指正,共同进步。