jsmubanlogo
  • 首页
  • 网页模板
  • 特效代码
  • 博文源码
  • 插件下载
  •    

java 后台防止重复提交幂等性判断

收藏    

作者第十天    2021-11-13

      

https://blog.csdn.net/weixin_44742132/article/details/107502899
5.最终版——封装
以上都是方法级别的实现方案,然而在实际的业务中,我们可能有很多的方法都需要防重,那么接下来我们就来封装一个公共的方法,以供所有类使用:

import org.apache.commons.collections4.map.LRUMap;
/**
 * 幂等性判断
 */
public class IdempotentUtils {
    // 根据 LRU(Least Recently Used,最近最少使用)算法淘汰数据的 Map 集合,最大容量 100 个
    private static LRUMap<String, Integer> reqCache = new LRUMap<>(100);
    /**
     * 幂等性判断
     * @return
     */
    public static boolean judge(String id, Object lockClass) {
        synchronized (lockClass) {
            // 重复请求判断
            if (reqCache.containsKey(id)) {
                // 重复请求
                System.out.println("请勿重复提交!!!" + id);
                return false;
            }
            // 非重复请求,存储请求 ID
            reqCache.put(id, 1);
        }
        return true;
    }
}
调用代码如下:

import com.example.idempote.util.IdempotentUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RequestMapping("/user")
@RestController
public class UserController4 {
    @RequestMapping("/add")
    public String addUser(String id) {
        // 非空判断(忽略)...
        // -------------- 幂等性调用(开始) --------------
        if (!IdempotentUtils.judge(id, this.getClass())) {
            return "执行失败";
        }
        // -------------- 幂等性调用(结束) --------------
        // 业务代码...
        System.out.println("添加用户ID:" + id);
        return "执行成功!";
    }


免责声明:
      1、 资源售价只是赞助,不代表代码或者素材本身价格。收取费用仅维持本站的日常运营所需。
      2、 本站资源来自用户上传,仅供用户学习使用,不得用于商业或者非法用途,违反国家法律一切后果用户自负。用于商业用途,请购买正版授权合法使用。
      3、 本站资源不保证其完整性和安全性,下载后自行检测安全,在使用过程中出现的任何问题均与本站无关,本站不承担任何技术及版权问题,不对任何资源负法律责任。
      4、 如有损害你的权益,请联系275551777@qq.com及时删除。

关于我们 | 积分获取 | 联系我们 | 用户协议 | 标签搜索 | 网站地图.html | 网站地图.xml | 网站地图.txt

Copyright © 2021-2023 All Right Reserved
陕公网安备 61082202000148号      陕ICP备2025078528号-1
js模板网 -陕西千手码农科技有限责任公司