畢業後一直作.Net工做,我喜歡C#更優美簡潔的語法(雖然有些關鍵字或者類的命名有點隱晦)。固然Java也不能丟掉,Java的不少開源技術更能讓我拓展視野,在分佈式方面也更容易上手。空餘時間正在將本身的一個我的項目用java重寫,設計爲一個分佈式的項目,其中有減庫存的操做。要作到全局同步,分佈式鎖正好用於解決此問題,在分佈式環境下,多線程共享臨界資源的場景下,分佈式鎖是一種很是重要的組件。Redis的單線程,setnx命令也是得天獨厚。java
我定義了一個接口,但願在未來作Redisson RedLock算法實現和ZK的分佈式鎖實現。下面lock是阻塞鎖,實現應包含重試機制,trylock是非阻塞鎖。redis
1 public interface DistributedLocker { 2 3 boolean lock(String key) throws InterruptedException; 4 5 boolean lock(String key,int expireSecond,int waitSecond) throws InterruptedException; 6 7 boolean tryLock(String key); 8 9 boolean tryLock(String key,int expireSecond); 10 11 boolean releaseLock(String key); 12 }
1 public class RedisLocker implements DistributedLocker { 2 3 private static ThreadLocal<String> threadLocal = new ThreadLocal<>(); 4 private JedisClient jedisClient; 5 6 public void setClient(JedisClient client) { 7 this.jedisClient = client; 8 } 9 10 private final int defaultExpireSeconds = 5; 11 12 private final int defaultWaitSeconds = 100; 13 14 @Override 15 public boolean lock(String key) throws InterruptedException { 16 17 return lock(key, defaultExpireSeconds, defaultWaitSeconds); 18 } 19 20 @Override 21 public boolean lock(String key, int expireSecond, int waitSecond) throws InterruptedException { 22 int maxDelayMillis = waitSecond * 1000; 23 boolean isLockSucceed=false; 24 while (maxDelayMillis>0){ 25 int delayTime = (int) (Math.random() * 20); 26 maxDelayMillis-=delayTime; 27 Thread.sleep(delayTime); 28 System.out.println("wait "+delayTime); 29 long startTime = System.currentTimeMillis(); 30 isLockSucceed= tryLock(key,expireSecond); 31 long endTime = System.currentTimeMillis(); 32 System.out.println("network"+(endTime-startTime)); 33 maxDelayMillis=maxDelayMillis-delayTime-(int)(endTime-startTime); 34 System.out.println("剩餘"+maxDelayMillis); 35 if (isLockSucceed){ 36 System.out.println("lock ok 剩餘"+maxDelayMillis); 37 break; 38 } 39 } 40 41 return isLockSucceed; 42 } 43 44 @Override 45 public boolean tryLock(String key) { 46 return tryLock(key, defaultExpireSeconds); 47 } 48 49 @Override 50 public boolean tryLock(String key, int expireSeconds) { 51 52 String lockToken = threadLocal.get(); 53 if (StringUtils.isBlank(lockToken)) { 54 System.out.println("token爲空" + lockToken); 55 lockToken = UUID.randomUUID().toString(); 56 threadLocal.set(lockToken); 57 } 58 59 boolean isLockSucceed = jedisClient.setNX(key, lockToken); 60 if (isLockSucceed) { //若是加鎖成功 61 jedisClient.expire(key, expireSeconds); 62 } else {//若是加鎖失敗 判斷是否應該重入 63 String tokenFromRedis = jedisClient.get(key); 64 System.out.println("tokenFromRedis:" + tokenFromRedis); 65 if (lockToken.equals(tokenFromRedis)) { 66 isLockSucceed = true;//可重入 67 System.out.println("重入成功"); 68 } 69 } 70 System.out.println("獲取鎖結果" + isLockSucceed + " token爲" + lockToken); 71 return isLockSucceed; 72 } 73 74 @Override 75 public boolean releaseLock(String key) { 76 return jedisClient.del(key); 77 } 78 }