Java 实现基于Redis的分布式可重入锁

如何实现可重入?

 

首先锁信息(指redis中lockKey关联的value值) 必须得设计的能负载更多信息,之前non-reentrant时value直接就是一个超时时间,但是要实现可重入单超时时间是不够的,必须要标识锁是被谁持有的,也就是说要标识分布式环境中的线程,还要记录锁被入了多少次。

 

 

如何在分布式线程中标识唯一线程?

 

MAC地址 +jvm进程 + 线程ID(或者线程地址都行),三者结合即可唯一分布式环境中的线程。下载

 

 

实现

 

锁的信息采用json存储,格式如下:

 

 

 

 代码框架还是和之前实现的非重入的差不多,重点是lock方法,代码已有非常详细的注释

 

Java代码 下载

  1. package cc.lixiaohui.lock.redis;  

  2.   

  3. import java.io.IOException;  

  4. import java.net.SocketAddress;  

  5. import java.util.concurrent.TimeUnit;  

  6.   

  7. import org.slf4j.Logger;  

  8. import org.slf4j.LoggerFactory;  

  9.   

  10. import redis.clients.jedis.Jedis;  

  11. import cc.lixiaohui.lock.AbstractLock;  

  12. import cc.lixiaohui.lock.Lock;  

  13. import cc.lixiaohui.lock.time.nio.client.TimeClient;  

  14. import cc.lixiaohui.lock.util.LockInfo;  

  15.   

  16. /** 

  17.  * 基于Redis的SETNX操作实现的分布式锁, 获取锁时最好用tryLock(long time, TimeUnit unit), 以免网路问题而导致线程一直阻塞. 

  18.  * <a href="http://redis.io/commands/setnx">SETNC操作参考资料.</a> 

  19.  *  

  20.  * <p><b>可重入实现关键:</b> 

  21.  * <ul> 

  22.  * <li>在分布式环境中如何确定一个线程? <i><b>mac地址 + jvm pid + threadId</b></i> (mac地址唯一, jvm 

  23.  * pid在单机内唯一, threadId在单jvm内唯一)</li> 

  24.  * <li>任何一个线程从redis拿到value值后都需要能确定 该锁是否被自己持有, 因此value值要有以下特性: 保存持有锁的主机(mac), jvm 

  25.  * pid, 持有锁的线程ID, 重复持有锁的次数</li> 

  26.  * </ul></p> 

  27.  * <p> 

  28.  * redis中value设计如下(in json): 

  29.  * <pre> 

  30.  * { 

  31.  *  expires : expire time in long 

  32.  *  mac : mac address of lock holder's machine 

  33.  *  pid : jvm process id 

  34.  *  threadId : lock holder thread id 

  35.  *  count : hold count(for use of reentrancy) 

  36.  * } 

  37.  * 由{@link LockInfo LockInfo}表示. 

  38.  * </pre> 

  39.  *  

  40.  * <b>Usage Example:</b> 

  41.  * <pre> 

  42.  *  {@link Lock} lock = new {@link ReentrantLock}(jedis, "lockKey", lockExpires, timeServerAddr); 

  43.  *  if (lock.tryLock(3, TimeUnit.SECONDS)) { 

  44.  *      try { 

  45.  *          // do something 

  46.  *      } catch (Exception e) { 

  47.  *          lock.unlock(); 

  48.  *      } 

  49.  *  } 

  50.  * </pre> 

  51.  * </p> 

  52.  *  

  53.  * @author lixiaohui 

  54.  * @date 2016年9月15日 下午2:52:38 

  55.  * 

  56.  */  

  57. public class ReentrantLock extends AbstractLock {  

  58.   

  59.     private Jedis jedis;  

  60.   

  61.     private TimeClient timeClient;  

  62.   

  63.     // 锁的名字  

  64.     protected String lockKey;  

  65.   

  66.     // 锁的有效时长(毫秒)  

  67.     protected long lockExpires;  

  68.   

  69.     private static final Logger logger = LoggerFactory.getLogger(ReentrantLock.class);  

  70.   

  71.     public ReentrantLock(Jedis jedis, String lockKey, long lockExpires, SocketAddress timeServerAddr) throws IOException {  

  72.         this.jedis = jedis;  

  73.         this.lockKey = lockKey;  

  74.         this.lockExpires = lockExpires;  

  75.         timeClient = new TimeClient(timeServerAddr);  

  76.     }  

  77.   

  78.     // 阻塞式获取锁的实现  

  79.     protected boolean lock(boolean useTimeout, long time, TimeUnit unit, boolean interrupt) throws InterruptedException {  

  80.         if (interrupt) {  

  81.             checkInterruption();  

  82.         }  

  83.   

  84.         // 超时控制 的时间可以从本地获取, 因为这个和锁超时没有关系, 只是一段时间区间的控制  

  85.         long start = localTimeMillis();  

  86.         long timeout = unit.toMillis(time); // if !useTimeout, then it's useless  

  87.   

  88.         // walkthrough  

  89.         // 1. lockKey未关联value, 直接设置lockKey, 成功获取到锁, return true  

  90.         // 2. lock 已过期, 用getset设置lockKey, 判断返回的旧的LockInfo  

  91.         // 2.1 若仍是超时的, 则成功获取到锁, return true  

  92.         // 2.2 若不是超时的, 则进入下一次循环重新开始 步骤1  

  93.         // 3. lock没过期, 判断是否是当前线程持有  

  94.         // 3.1 是, 则计数加 1, return true  

  95.         // 3.2 否, 则进入下一次循环重新开始 步骤1  

  96.         // note: 每次进入循环都检查 : 1.是否超时, 若是则return false; 2.是否检查中断(interrupt)被中断,  

  97.         // 若需检查中断且被中断, 则抛InterruptedException  

  98.         while (useTimeout ? !isTimeout(start, timeout) : true) {  

  99.             if (interrupt) {  

  100.                 checkInterruption();  

  101.             }  

  102.   

  103.             long lockExpireTime = serverTimeMillis() + lockExpires + 1;// 锁超时时间  

  104.             String newLockInfoJson = LockInfo.newForCurrThread(lockExpireTime).toString();  

  105.             if (jedis.setnx(lockKey, newLockInfoJson) == 1) { // 条件能成立的唯一情况就是redis中lockKey还未关联value  

  106.                 // TODO 成功获取到锁, 设置相关标识  

  107.                 logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);  

  108.                 locked = true;  

  109.                 return true;  

  110.             }  

  111.   

  112.             // value已有值, 但不能说明锁被持有, 因为锁可能expired了  

  113.             String currLockInfoJson = jedis.get(lockKey);  

  114.             // 若这瞬间锁被delete了  

  115.             if (currLockInfoJson == null) {  

  116.                 continue;  

  117.             }  

  118.   

  119.             LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);  

  120.             // 竞争条件只可能出现在锁超时的情况, 因为如果没有超时, 线程发现锁并不是被自己持有, 线程就不会去动value  

  121.             if (isTimeExpired(currLockInfo.getExpires())) {  

  122.                 // 锁超时了  

  123.                 LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfoJson));  

  124.                 if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {  

  125.                     // TODO 成功获取到锁, 设置相关标识  

  126.                     logger.debug("{} get lock(new), lockInfo: {}", Thread.currentThread().getName(), newLockInfoJson);  

  127.                     locked = true;  

  128.                     return true;  

  129.                 }  

  130.             } else {  

  131.                 // 锁未超时, 不会有竞争情况  

  132.                 if (isHeldByCurrentThread(currLockInfo)) { // 当前线程持有  

  133.                     // TODO 成功获取到锁, 设置相关标识  

  134.                     currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1); // 设置新的锁超时时间  

  135.                     currLockInfo.incCount();  

  136.                     jedis.set(lockKey, currLockInfo.toString());  

  137.                     logger.debug("{} get lock(inc), lockInfo: {}", Thread.currentThread().getName(), currLockInfo);  

  138.                     locked = true;  

  139.                     return true;  

  140.                 }  

  141.             }  

  142.         }  

  143.         locked = false;  

  144.         return false;  

  145.     }  

  146.   

  147.     public boolean tryLock() {  

  148.         long lockExpireTime = serverTimeMillis() + lockExpires + 1;  

  149.         String newLockInfo = LockInfo.newForCurrThread(lockExpireTime).toString();  

  150.   

  151.         if (jedis.setnx(lockKey, newLockInfo) == 1) {  

  152.             locked = true;  

  153.             return true;  

  154.         }  

  155.   

  156.         String currLockInfoJson = jedis.get(lockKey);  

  157.         if (currLockInfoJson == null) {  

  158.             // 再一次尝试获取  

  159.             if (jedis.setnx(lockKey, newLockInfo) == 1) {  

  160.                 locked = true;  

  161.                 return true;  

  162.             } else {  

  163.                 locked = false;  

  164.                 return false;  

  165.             }  

  166.         }  

  167.           

  168.         LockInfo currLockInfo = LockInfo.fromString(currLockInfoJson);  

  169.           

  170.         if (isTimeExpired(currLockInfo.getExpires())) {  

  171.             LockInfo oldLockInfo = LockInfo.fromString(jedis.getSet(lockKey, newLockInfo));  

  172.             if (oldLockInfo != null && isTimeExpired(oldLockInfo.getExpires())) {  

  173.                 locked = true;  

  174.                 return true;  

  175.             }  

  176.         } else {  

  177.             if (isHeldByCurrentThread(currLockInfo)) {  

  178.                 currLockInfo.setExpires(serverTimeMillis() + lockExpires + 1);   

  179.                 currLockInfo.incCount();  

  180.                 jedis.set(lockKey, currLockInfo.toString());  

  181.                 locked = true;  

  182.                 return true;  

  183.             }  

  184.         }  

  185.         locked = false;  

  186.         return false;  

  187.     }  

  188.   

  189.     /** 

  190.      * Queries if this lock is held by any thread. 

  191.      *  

  192.      * @return {@code true} if any thread holds this lock and {@code false} 

  193.      *         otherwise 

  194.      */  

  195.     public boolean isLocked() {  

  196.         // walkthrough  

  197.         // 1. lockKey未关联value, return false  

  198.         // 2. 若 lock 已过期, return false, 否则 return true  

  199.         if (!locked) { // 本地locked为false, 肯定没加锁  

  200.             return false;  

  201.         }  

  202.         String json = jedis.get(lockKey);  

  203.         if (json == null) {  

  204.             return false;  

  205.         }  

  206.         if (isTimeExpired(LockInfo.fromString(json).getExpires())) {  

  207.             return false;  

  208.         }  

  209.         return true;  

  210.     }  

  211.   

  212.     @Override  

  213.     protected void unlock0() {  

  214.         // walkthrough  

  215.         // 1. 若锁过期, return  

  216.         // 2. 判断自己是否是锁的owner  

  217.         // 2.1 是, 若 count = 1, 则删除lockKey; 若 count > 1, 则计数减 1, return  

  218.         // 2.2 否, 则抛异常 IllegalMonitorStateException, reutrn  

  219.         // done, return  

  220.         LockInfo currLockInfo = LockInfo.fromString(jedis.get(lockKey));  

  221.         if (isTimeExpired(currLockInfo.getExpires())) {  

  222.             return;  

  223.         }  

  224.   

  225.         if (isHeldByCurrentThread(currLockInfo)) {  

  226.             if (currLockInfo.getCount() == 1) {  

  227.                 jedis.del(lockKey);  

  228.                 logger.debug("{} unlock(del), lockInfo: null", Thread.currentThread().getName());  

  229.             } else {  

  230.                 currLockInfo.decCount(); // 持有锁计数减1  

  231.                 String json = currLockInfo.toString();  

  232.                 jedis.set(lockKey, json);  

  233.                 logger.debug("{} unlock(dec), lockInfo: {}", Thread.currentThread().getName(), json);  

  234.             }  

  235.         } else {  

  236.             throw new IllegalMonitorStateException(String.format("current thread[%s] does not holds the lock", Thread.currentThread().toString()));  

  237.         }  

  238.   

  239.     }  

  240.   

  241.     public void release() {  

  242.         jedis.close();  

  243.         timeClient.close();  

  244.     }  

  245.       

  246.     public boolean isHeldByCurrentThread() {  

  247.         return isHeldByCurrentThread(LockInfo.fromString(jedis.get(lockKey)));  

  248.     }  

  249.   

  250.     // ------------------- utility methods ------------------------  

  251.   

  252.     private boolean isHeldByCurrentThread(LockInfo lockInfo) {  

  253.         return lockInfo.isCurrentThread();  

  254.     }  

  255.   

  256.     private void checkInterruption() throws InterruptedException {  

  257.         if (Thread.currentThread().isInterrupted()) {  

  258.             throw new InterruptedException();  

  259.         }  

  260.     }  

  261.   

  262.     private boolean isTimeExpired(long time) {  

  263.         return time < serverTimeMillis();  

  264.     }  

  265.   

  266.     private boolean isTimeout(long start, long timeout) {  

  267.         // 这里拿本地的时间来比较  

  268.         return start + timeout < System.currentTimeMillis();  

  269.     }  

  270.   

  271.     private long serverTimeMillis() {  

  272.         return timeClient.currentTimeMillis();  

  273.     }  

  274.   

  275.     private long localTimeMillis() {  

  276.         return System.currentTimeMillis();  

  277.     }  

  278.   

  279. }  

 

 测试

 

5个线程,每个线程都是不同的jedis连接,模拟分布式环境,线程的任务就是不断的去尝试重入地获取锁,重入的次数为随机但在0-5之间。

 

代码

 

Java代码   下载

  1. package cc.lixiaohui.DistributedLock.DistributedLock;  

  2.   

  3. import java.io.IOException;  

  4. import java.net.InetSocketAddress;  

  5. import java.net.SocketAddress;  

  6. import java.util.ArrayList;  

  7. import java.util.List;  

  8. import java.util.Random;  

  9. import java.util.concurrent.TimeUnit;  

  10.   

  11. import org.junit.Test;  

  12.   

  13. import redis.clients.jedis.Jedis;  

  14. import cc.lixiaohui.lock.redis.ReentrantLock;  

  15.   

  16. /** 

  17.  * @author lixiaohui 

  18.  * @date 2016年9月28日 下午8:41:36 

  19.  *  

  20.  */  

  21. public class ReentrantTest {  

  22.       

  23.     final int EXPIRES = 10 * 1000;  

  24.       

  25.     final String LOCK_KEY = "lock.lock";  

  26.       

  27.     final SocketAddress TIME_SERVER_ADDR = new InetSocketAddress("localhost"9999);  

  28.       

  29.     @Test  

  30.     public void test() throws Exception {  

  31.         // 创建5个线程不停地去重入(随机次数n, 0 <= n <=5)获取锁  

  32.         List<Thread> threads = createThreads(5);  

  33.         //开始任务  

  34.         for (Thread t : threads) {  

  35.             t.start();  

  36.         }  

  37.         // 执行60秒  

  38.         Thread.sleep(60 * 1000);  

  39.         //停止所有线程  

  40.         Task.alive = false;  

  41.         // 等待所有线程终止  

  42.         for (Thread t : threads) {  

  43.             t.join();  

  44.         }  

  45.           

  46.     }  

  47.     // 创建count个线程,每个线程都是不同的jedis连接以及不同的与时间服务器的连接  

  48.     private List<Thread> createThreads(int count) throws IOException {  

  49.         List<Thread> threads = new ArrayList<Thread>();  

  50.         for (int i = 0; i < count; i++) {  

  51.             Jedis jedis = new Jedis("localhost"6379);  

  52.             ReentrantLock lock = new ReentrantLock(jedis, LOCK_KEY, EXPIRES, TIME_SERVER_ADDR);  

  53.             Task task = new Task(lock);  

  54.             Thread t = new Thread(task);  

  55.             threads.add(t);  

  56.         }  

  57.         return threads;  

  58.     }  

  59.       

  60.     private static class Task implements Runnable {  

  61.           

  62.         private ReentrantLock lock;  

  63.           

  64.         private final int MAX_ENTRANT = 5;  

  65.           

  66.         private final Random random = new Random();  

  67.           

  68.         private static boolean alive = true;  

  69.           

  70.         Task(ReentrantLock lock) {  

  71.             this.lock = lock;  

  72.         }  

  73.           

  74.         public void run() {  

  75.             while (alive) {  

  76.                 int times = random.nextInt(MAX_ENTRANT);  

  77.                 doLock(times);  

  78.             }  

  79.         }  

  80.           

  81.         private void doLock(int times) {  

  82.             if (lock.tryLock(5, TimeUnit.SECONDS)) {  

  83.                 try {  

  84.                     if (times > 0) {  

  85.                         doLock(--times);  

  86.                     }  

  87.                 } finally {  

  88.                     if (lock != null) {  

  89.                         lock.unlock();  

  90.                     }  

  91.                 }  

  92.             }  

  93.               

  94.         }  

  95.           

  96.           

  97.           

  98.     }  

  99.       

  100. }  

 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章