From 790255f73351a4e1dd93e565ccc7f612b989d8eb Mon Sep 17 00:00:00 2001 From: wangkang Date: Thu, 21 Dec 2017 08:52:37 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9F=BA=E4=BA=8Eredis=E7=9A=84=E5=88=86?= =?UTF-8?q?=E5=B8=83=E5=BC=8F=E9=94=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../redis/lock/RedisBasedDistributedLock.java | 79 +++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 udf-starter-cache-redis/src/main/java/org/itkk/udf/cache/redis/lock/RedisBasedDistributedLock.java diff --git a/udf-starter-cache-redis/src/main/java/org/itkk/udf/cache/redis/lock/RedisBasedDistributedLock.java b/udf-starter-cache-redis/src/main/java/org/itkk/udf/cache/redis/lock/RedisBasedDistributedLock.java new file mode 100644 index 0000000..ca5c49f --- /dev/null +++ b/udf-starter-cache-redis/src/main/java/org/itkk/udf/cache/redis/lock/RedisBasedDistributedLock.java @@ -0,0 +1,79 @@ +package org.itkk.udf.cache.redis.lock; + +import org.itkk.udf.cache.redis.CacheRedisProperties; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Component; + +import java.util.concurrent.TimeUnit; + +/** + * RedisBasedDistributedLock + */ +@Component +public class RedisBasedDistributedLock { + + /** + * DISTRIBUTED_LOCK_KEY_PREFIX + */ + private static final String DISTRIBUTED_LOCK_KEY_PREFIX = ":DISTRIBUTED_LOCK:"; + + /** + * redisTemplate + */ + @Autowired + private RedisTemplate redisTemplate; + + /** + * cacheRedisProperties + */ + @Autowired + private CacheRedisProperties cacheRedisProperties; + + /** + * lock + * + * @param name name + * @param timeout timeout + * @param timeUnit timeUnit + * @param lockValue lockValue + * @param + * @return boolean + */ + public boolean lock(String name, long timeout, TimeUnit timeUnit, T lockValue) { + //获得key + String key = cacheRedisProperties.getPrefix() + DISTRIBUTED_LOCK_KEY_PREFIX + name; + //检查是否是死锁 + if (redisTemplate.hasKey(key)) { + //获得缓存过期时间 + long expiration = redisTemplate.getExpire(key); + //如果等于-1,则代表死锁 + if (expiration == -1) { + //删除缓存 + redisTemplate.delete(key); + } + } + //创建锁 + boolean lock = redisTemplate.opsForValue().setIfAbsent(key, lockValue); + //锁成功 + if (lock) { + //设置超时时间 + redisTemplate.expire(key, timeout, timeUnit); + } + //返回 + return lock; + } + + /** + * unlock + * + * @param name name + */ + public void unlock(String name) { + //获得key + String key = cacheRedisProperties.getPrefix() + DISTRIBUTED_LOCK_KEY_PREFIX + name; + //删除缓存 + redisTemplate.delete(key); + } + +}