2024-07-12
한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina
gitee address (need to pick up by yourself)AopProxy duplicate submission: prevent duplicate submission (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("禁止重复提交");
- // }
- }
- }
The idea is to use a proxy to execute the method, slice it using the idea of AOP, add a distributed lock before executing the method. Here, the distributed lock uses redis.nx, and adds an expiration time to prevent deadlock. I only did a simple simulation as a whole, and it is relatively simple to write. If there are any errors or deficiencies, please correct me and make progress together.