概述
目前幾乎很多大型網站及應用都是分布式部署的,分布式場景中的數據一致性問題一直是一個比較重要的話題。分布式的CAP理論告訴我們“任何一個分布式系統都無法同時滿足一致性(Consistency)、可用性(Availability)和分區容錯性(Partition tolerance),最多只能同時滿足兩項。”所以,很多系統在設計之初就要對這三者做出取舍。在互聯網領域的絕大多數的場景中,都需要犧牲強一致性來換取系統的高可用性,系統往往只需要保證“最終一致性”,只要這個最終時間是在用戶可以接受的范圍內即可。
在很多場景中,我們為了保證數據的最終一致性,需要很多的技術方案來支持,比如分布式事務、分布式鎖等。
選用Redis實現分布式鎖原因
- Redis有很高的性能
- Redis命令對此支持較好,實現起來比較方便
在此就不介紹Redis的安裝了,具體在Linux和Windows中的安裝可以查看我前面的博客。
http://www.cnblogs.com/liuyang0/p/6504826.html
使用命令介紹
SETNX
SETNX key val
當且僅當key不存在時,set一個key為val的字符串,返回1;若key存在,則什么都不做,返回0。
expire
expire key timeout
為key設置一個超時時間,單位為second,超過這個時間鎖會自動釋放,避免死鎖。
delete
delete key
刪除key
在使用Redis實現分布式鎖的時候,主要就會使用到這三個命令。
實現
使用的是jedis來連接Redis。
實現思想
- 獲取鎖的時候,使用setnx加鎖,并使用expire命令為鎖添加一個超時時間,超過該時間則自動釋放鎖,鎖的value值為一個隨機生成的UUID,通過此在釋放鎖的時候進行判斷。
- 獲取鎖的時候還設置一個獲取的超時時間,若超過這個時間則放棄獲取鎖。
- 釋放鎖的時候,通過UUID判斷是不是該鎖,若是該鎖,則執行delete進行鎖釋放。
分布式鎖的核心代碼如下:
1 package com.distribute; 2 3 import redis.clients.jedis.Jedis; 4 import redis.clients.jedis.JedisPool; 5 import redis.clients.jedis.Transaction; 6 import redis.clients.jedis.exceptions.JedisException; 7 8 import java.util.List; 9 import java.util.UUID; 10 11 /** 12 * Created by liuyang on 2017/4/20. 13 */ 14 public class DistributedLock { 15 private final JedisPool jedisPool; 16 17 public DistributedLock(JedisPool jedisPool) { 18 this.jedisPool = jedisPool; 19 } 20 21 /** 22 * 加鎖 23 * 24 * @param locaName 鎖的key 25 * @param acquireTimeout 獲取超時時間 26 * @param timeout 鎖的超時時間 27 * @return 鎖標識 28 */ 29 public String lockWithTimeout(String locaName, long acquireTimeout, long timeout) { 30 Jedis conn = null; 31 String retIdentifier = null; 32 try { 33 // 獲取連接 34 conn = jedisPool.getResource(); 35 // 隨機生成一個value 36 String identifier = UUID.randomUUID().toString(); 37 // 鎖名,即key值 38 String lockKey = "lock:" + locaName; 39 // 超時時間,上鎖后超過此時間則自動釋放鎖 40 int lockExpire = (int) (timeout / 1000); 41 42 // 獲取鎖的超時時間,超過這個時間則放棄獲取鎖 43 long end = System.currentTimeMillis() + acquireTimeout; 44 while (System.currentTimeMillis() < end) { 45 if (conn.setnx(lockKey, identifier) == 1) { 46 conn.expire(lockKey, lockExpire); 47 // 返回value值,用于釋放鎖時間確認 48 retIdentifier = identifier; 49 return retIdentifier; 50 } 51 // 返回-1代表key沒有設置超時時間,為key設置一個超時時間 52 if (conn.ttl(lockKey) == -1) { 53 conn.expire(lockKey, lockExpire); 54 } 55 56 try { 57 Thread.sleep(10); 58 } catch (InterruptedException e) { 59 Thread.currentThread().interrupt(); 60 } 61 } 62 } catch (JedisException e) { 63 e.printStackTrace(); 64 } finally { 65 if (conn != null) { 66 conn.close(); 67 } 68 } 69 return retIdentifier; 70 } 71 72 /** 73 * 釋放鎖 74 * 75 * @param lockName 鎖的key 76 * @param identifier 釋放鎖的標識 77 * @return 78 */ 79 public boolean releaseLock(String lockName, String identifier) { 80 Jedis conn = null; 81 String lockKey = "lock:" + lockName; 82 boolean retFlag = false; 83 try { 84 conn = jedisPool.getResource(); 85 while (true) { 86 // 監視lock,準備開始事務 87 conn.watch(lockKey); 88 // 通過前面返回的value值判斷是不是該鎖,若是該鎖,則刪除,釋放鎖 89 if (identifier.equals(conn.get(lockKey))) { 90 Transaction transaction = conn.multi(); 91 transaction.del(lockKey); 92 List<Object> results = transaction.exec(); 93 if (results == null) { 94 continue; 95 } 96 retFlag = true; 97 } 98 conn.unwatch(); 99 break; 100 } 101 } catch (JedisException e) { 102 e.printStackTrace(); 103 } finally { 104 if (conn != null) { 105 conn.close(); 106 } 107 } 108 return retFlag; 109 } 110 }
測試
下面就用一個簡單的例子測試剛才實現的分布式鎖。
例子中使用50個線程模擬秒殺一個商品,使用--運算符來實現商品減少,從結果有序性就可以看出是否為加鎖狀態。
模擬秒殺服務,在其中配置了jedis線程池,在初始化的時候傳給分布式鎖,供其使用。
1 import redis.clients.jedis.JedisPool; 2 import redis.clients.jedis.JedisPoolConfig; 3 4 /** 5 * Created by liuyang on 2017/4/20. 6 */ 7 public class Service { 8 private static JedisPool pool = null; 9 10 static { 11 JedisPoolConfig config = new JedisPoolConfig(); 12 // 設置最大連接數 13 config.setMaxTotal(200); 14 // 設置最大空閑數 15 config.setMaxIdle(8); 16 // 設置最大等待時間 17 config.setMaxWaitMillis(1000 * 100); 18 // 在borrow一個jedis實例時,是否需要驗證,若為true,則所有jedis實例均是可用的 19 config.setTestOnBorrow(true); 20 pool = new JedisPool(config, "127.0.0.1", 6379, 3000); 21 } 22 23 DistributedLock lock = new DistributedLock(pool); 24 25 int n = 500; 26 27 public void seckill() { 28 // 返回鎖的value值,供釋放鎖時候進行判斷 29 String indentifier = lock.lockWithTimeout("resource", 5000, 1000); 30 System.out.println(Thread.currentThread().getName() + "獲得了鎖"); 31 System.out.println(--n); 32 lock.releaseLock("resource", indentifier); 33 } 34 }
?
// 模擬線程進行秒殺服務
1 public class ThreadA extends Thread { 2 private Service service; 3 4 public ThreadA(Service service) { 5 this.service = service; 6 } 7 8 @Override 9 public void run() { 10 service.seckill(); 11 } 12 } 13 14 public class Test { 15 public static void main(String[] args) { 16 Service service = new Service(); 17 for (int i = 0; i < 50; i++) { 18 ThreadA threadA = new ThreadA(service); 19 threadA.start(); 20 } 21 } 22 }
?
結果如下,結果為有序的。
1 public void seckill() { 2 // 返回鎖的value值,供釋放鎖時候進行判斷 3 //String indentifier = lock.lockWithTimeout("resource", 5000, 1000); 4 System.out.println(Thread.currentThread().getName() + "獲得了鎖"); 5 System.out.println(--n); 6 //lock.releaseLock("resource", indentifier); 7 }
從結果可以看出,有一些是異步進行的。
在分布式環境中,對資源進行上鎖有時候是很重要的,比如搶購某一資源,這時候使用分布式鎖就可以很好地控制資源。
當然,在具體使用中,還需要考慮很多因素,比如超時時間的選取,獲取鎖時間的選取對并發量都有很大的影響,上述實現的分布式鎖也只是一種簡單的實現,主要是一種思想。
下一次我會使用zookeeper實現分布式鎖,使用zookeeper的可靠性是要大于使用redis實現的分布式鎖的,但是相比而言,redis的性能更好。
上面的代碼可以在我的GitHub中進行查看,地址如下:
https://github.com/yangliu0/DistributedLock