Redis分布式鎖

來源:互聯網
上載者:User

標籤:redis分布式   nts   default   col   分布   port   ESS   The   ted   

 1 package com.zad.jedis; 2  3 import redis.clients.jedis.Jedis; 4  5 import java.util.Collections; 6  7 /** 8  * 描述: 9  * 分布式鎖10  *11  * @author zad12  * @create 2018-09-14 13:5813  */14 public class Distributed {15     private static final String LOCK_SUCCESS = "OK";16     private static final String SET_IF_NOT_EXIST = "NX";17     private static final String SET_WITH_EXPIRE_TIME = "PX";18     private static final Integer RELEASE_SUCCESS = 1;19     private static final Integer DEFAULT_TIME = 5;20 21     /**22      * 嘗試擷取分布式鎖23      *24      * @param jedis      Redis用戶端25      * @param lockKey    鎖26      * @param requestId  請求標識27      * @return 是否擷取成功28      */29     public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId) {30 31         String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, DEFAULT_TIME);32 33         if (LOCK_SUCCESS.equals(result)) {34             return true;35         }36         return false;37 38     }39 40 41     /**42      * 嘗試擷取分布式鎖43      *44      * @param jedis      Redis用戶端45      * @param lockKey    鎖46      * @param requestId  請求標識47      * @param expireTime 超期時間48      * @return 是否擷取成功49      */50     public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {51 52         String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireTime);53 54         if (LOCK_SUCCESS.equals(result)) {55             return true;56         }57         return false;58 59     }60 61     /**62      * 釋放分布式鎖63      *64      * @param jedis     Redis用戶端65      * @param lockKey   鎖66      * @param requestId 請求標識67      * @return 是否釋放成功68      */69     public static boolean releaseDistributedLock(Jedis jedis, String lockKey, String requestId) {70 71         String script = "if redis.call(‘get‘, KEYS[1]) == ARGV[1] then return redis.call(‘del‘, KEYS[1]) else return 0 end";72         Object result = jedis.eval(script, Collections.singletonList(lockKey), Collections.singletonList(requestId));73 74         if (RELEASE_SUCCESS.equals(result)) {75             return true;76         }77         return false;78 79     }80 }

 

Redis分布式鎖

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.