Created
March 5, 2019 12:09
-
-
Save qlong8807/5fa18af7808dd3aff55945b749d4b55b to your computer and use it in GitHub Desktop.
redis实现分布式锁。springboot下注入redisTemplate,redis的expire、delete等操作需要用redisTemplate而不能用opsForValue等。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.data.redis.core.RedisCallback; | |
import org.springframework.data.redis.core.RedisTemplate; | |
import org.springframework.stereotype.Component; | |
import java.util.Objects; | |
@Component("redisHelper") | |
public class RedisHelper { | |
@Autowired | |
private RedisTemplate redisTemplate; | |
public static final String LOCK_PREFIX = "redis_lock"; | |
/** | |
* 分布式锁 | |
* | |
* @param key key值 | |
* @param lock_expire 锁的过期时间,单位是毫秒 | |
* @return 是否获取到锁,true为获取到锁,false为未获取到。 | |
*/ | |
public boolean lock(String key,int lock_expire) { | |
String lock = LOCK_PREFIX + key; | |
return (Boolean) redisTemplate.execute((RedisCallback) connection -> { | |
long expireAt = System.currentTimeMillis() + lock_expire; | |
Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes()); | |
if (acquire) { | |
return true; | |
} else { | |
byte[] value = connection.get(lock.getBytes()); | |
if (Objects.nonNull(value) && value.length > 0) { | |
long expireTime = Long.parseLong(new String(value)); | |
if (expireTime < System.currentTimeMillis()) { | |
// 如果锁已经过期 | |
byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + lock_expire).getBytes()); | |
// 防止死锁 | |
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis(); | |
} | |
} | |
} | |
return false; | |
}); | |
} | |
/** | |
* 删除锁 | |
* @param key | |
*/ | |
public void delete(String key) { | |
redisTemplate.delete(key); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment