本文主要是介绍redis 并发锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
public static void main(String[] args) {
String value = UUID.randomUUID() + ":" + Thread.currentThread().getName();
long tryTime = 100000L;
long expireTime = 100000L;
String key = "lock";
JedisPool jedisPool = new JedisPool();
Jedis jedis = jedisPool.getResource();
for (int i = 0; i < 10; i++) {
System.out.println(getlock(jedis, key, value, tryTime, expireTime));
}
for (int i = 0; i < 10; i++) {
System.out.println(releaseLock(jedis, key, value, tryTime));
}
}
/**
*
* @param jedis
* @param key key
* @param value 重如锁value
* @param tryTime 重试时间
* @return result
*/
private static Object releaseLock(Jedis jedis, String key, String value, long tryTime) {
String script = "if (redis.call('exists', KEYS[1]) == 0) then " +
"return 0;" +
"end;" +
"if(redis.call('hexists', KEYS[1], ARGV[1]) == 1) then " +
"local lo = redis.call('hincrby',KEYS[1],ARGV[1], -1)" +
"if(lo < 1) then " +
"redis.call('del', KEYS[1]);" +
"return lo;" +
"end;" +
"return lo;" +
"end;" +
"return -1;";
final long endTime = tryTime + System.currentTimeMillis();
while (true) {
Object res = jedis.eval(script, Collections.singletonList(key), Collections.singletonList(value));
if (Integer.parseInt(String.valueOf(res)) >= 0) {
return true;
}
if (System.currentTimeMillis() - endTime > 0) {
return false;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("sleep error");
}
}
}
/**
*
* @param jedis
* @param key key
* @param value 重如锁value
* @param tryTime 重试时间
* @param expireTime key过期时间
* @return result
*/
private static boolean getlock(Jedis jedis, String key, String value, long tryTime, long expireTime) {
final long endTime = tryTime + System.currentTimeMillis();
String script = "if (redis.call('exists', KEYS[1]) == 0) then " +
"redis.call('hset', KEYS[1], ARGV[1], 1);" +
"redis.call('pexpire', KEYS[1], ARGV[2]);" +
"return 1;" +
"end;" +
"if(redis.call('hexists', KEYS[1], ARGV[1]) == 1) then " +
"redis.call('pexpire', KEYS[1], ARGV[2]);" +
"return redis.call('hincrby',KEYS[1],ARGV[1],1);" +
"end;" +
"return 0;";
while (true) {
Object res = jedis.eval(script, Collections.singletonList(key), Arrays.asList(value, expireTime+""));
if (Integer.parseInt(String.valueOf(res)) > 0) {
return true;
}
if (System.currentTimeMillis() - endTime > 0) {
return false;
}
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
System.out.println("sleep error");
}
}
}
这篇关于redis 并发锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!