package org.onetwo.boot.module.redis;
/**
 * @author weishao zeng
 * <br/>
 */

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.function.Supplier;

import org.onetwo.common.exception.BaseException;
import org.springframework.integration.redis.util.RedisLockRegistry;

public class RedisLockService {
	
	private RedisLockRegistry redisLockRegistry;
	
	public RedisLockService(RedisLockRegistry redisLockRegistry) {
		super();
		this.redisLockRegistry = redisLockRegistry;
	}

	public void tryLock(String lockKey, long timeInMillis, Runnable action) {
		Lock locker = redisLockRegistry.obtain(lockKey);
		try {
			locker.tryLock(timeInMillis, TimeUnit.MILLISECONDS);
			action.run();
		} catch (InterruptedException e) {
			throw new BaseException("lock[" + lockKey + "] has interrupted!");
		} finally {
			locker.unlock();
		}
	}
	
	public <T> T lock(String lockKey, long timeInMillis, Supplier<T> action) {
		Lock locker = redisLockRegistry.obtain(lockKey);
		try {
			locker.tryLock(timeInMillis, TimeUnit.MILLISECONDS);
			return action.get();
		} catch (InterruptedException e) {
			throw new BaseException("lock[" + lockKey + "] has interrupted!");
		} finally {
			locker.unlock();
		}
	}
	
	public void lock(String lockKey, Runnable action) {
		Lock locker = redisLockRegistry.obtain(lockKey);
		try {
			locker.lock();
			action.run();
		} finally {
			locker.unlock();
		}
	}
	
	public <T> T lock(String lockKey, Supplier<T> action) {
		Lock locker = redisLockRegistry.obtain(lockKey);
		try {
			locker.lock();
			return action.get();
		} finally {
			locker.unlock();
		}
	}

}

@@ -639,33 +639,68 @@
 lockKey);%0A%09%09
-try %7B%0A%09%09%09
+boolean locked = false;%0A%09%09try %7B%0A%09%09%09locked = 
 locker.tryLo
@@ -740,16 +740,34 @@
 CONDS);%0A
+%09%09%09if (locked) %7B%0A%09
 %09%09%09actio
@@ -771,24 +771,29 @@
 tion.run();%0A
+%09%09%09%7D%0A
 %09%09%7D catch (I
@@ -893,32 +893,50 @@
 ;%0A%09%09%7D finally %7B%0A
+%09%09%09if (locked) %7B%0A%09
 %09%09%09locker.unlock
@@ -931,32 +931,37 @@
 ocker.unlock();%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%09%0A%09public
@@ -959,33 +959,36 @@
 %09%0A%09public %3CT%3E T 
-l
+tryL
 ock(String lockK
@@ -1075,32 +1075,58 @@
 btain(lockKey);%0A
+%09%09boolean locked = false;%0A
 %09%09try %7B%0A%09%09%09locke
@@ -1116,24 +1116,33 @@
 %0A%09%09try %7B%0A%09%09%09
+locked = 
 locker.tryLo
@@ -1182,16 +1182,34 @@
 CONDS);%0A
+%09%09%09if (locked) %7B%0A%09
 %09%09%09retur
@@ -1220,24 +1220,45 @@
 tion.get();%0A
+%09%09%09%7D%0A%09%09%09return null;%0A
 %09%09%7D catch (I
@@ -1358,32 +1358,50 @@
 ;%0A%09%09%7D finally %7B%0A
+%09%09%09if (locked) %7B%0A%09
 %09%09%09locker.unlock
@@ -1396,32 +1396,37 @@
 ocker.unlock();%0A
+%09%09%09%7D%0A
 %09%09%7D%0A%09%7D%0A%09%0A%09public

fix redis lock service