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

  • 相关阅读:
    *HDU2473 并查集
    *HDU3172 并查集
    *cf.4 贪心
    *HDU3635 并查集
    *HDU1325 并查集
    *HDU1829 并查集
    Node.js 学习笔记二
    Node.js 学习笔记 一
    AngularJS 学习笔记 一
    MongoDB 基础知识二
  • 原文地址:https://www.cnblogs.com/wujf/p/15720526.html
Copyright © 2011-2022 走看看