zoukankan      html  css  js  c++  java
  • 顺手写的redis分布式锁

        /**
         * 锁定一个key,***一定要手工释放锁
         * 
         * @param key
         * @return
         */
        public boolean lockKey(String key) {
            return redisTemplate.opsForValue().setIfAbsent(key, 0);
        }
    
        /**
         * 锁定一个key,指定锁定时间
         * 
         * @param key
         * @param time
         * @return
         */
        public boolean lockKey(String key, int locktime) {
            return redisTemplate.opsForValue().setIfAbsent(key, 0, locktime, TimeUnit.SECONDS);
        }
    
        /**
         * 自旋加锁
         * 
         * @param key
         * @param trytime
         * @return
         */
        public boolean lockKeySpin(String key, int trytime, long sleepTime) {
            for (int i = 0; i < trytime; i++) {
                boolean flag = redisTemplate.opsForValue().setIfAbsent(key, 0);
                if (flag)
                    return true;
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    continue;
                }
            }
            return false;
        }
    
        /**
         * 锁定一个key,指定锁定时间,***一定要手工释放锁
         * 
         * @param key
         * @param trytime
         * @param sleepTime
         * @param locktime
         * @return
         */
        public boolean lockKeySpin(String key, int trytime, long sleepTime, int locktime) {
            for (int i = 0; i < trytime; i++) {
                boolean flag = redisTemplate.opsForValue().setIfAbsent(key, 0, locktime, TimeUnit.SECONDS);
                if (flag)
                    return true;
                try {
                    Thread.sleep(sleepTime);
                } catch (InterruptedException e) {
                    continue;
                }
            }
            return false;
        }
    
        /**
         * 释放锁
         * 
         * @param key
         * @return
         */
        public boolean unlockKey(String key) {
            return redisTemplate.delete(key);
        }

    后台兼职接单中,联系我微信:wjf88520

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    PHP + JQuery 实现多图上传并预览
    推荐40个专业的CMS下载
    10 个有用的 PHP 代码
    2012年最值得关注最具颠覆性的10个创业公司
    在线生成 CSS3 的工具
    循环显示/隐藏图片
    100个推荐的图片/内容滑动条
    jQuery 下拉菜单插件
    20个网站测试工具
    20个免费在线生成网站
  • 原文地址:https://www.cnblogs.com/wujf/p/15720526.html
Copyright © 2011-2022 走看看