RedisLock
自己实现一个Redis分布式锁
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;
/**
* @author lijiayin
*/
public class RedisLock {
private static final String REDIS_LOCK_KEY_PREFIX = "redis_lock_";
private static StringRedisTemplate redisTemplate;
static {
redisTemplate = SpringContextHolder.getBean(StringRedisTemplate.class);
}
@SuppressWarnings("all")
public static boolean lock(String key, Long duration){
key = REDIS_LOCK_KEY_PREFIX + key;
Boolean success = redisTemplate.opsForValue().setIfAbsent(key,
String.valueOf(System.currentTimeMillis() + duration));
if(success){
redisTemplate.expire(key, duration, TimeUnit.MILLISECONDS);
} else {
String oldValue = redisTemplate.opsForValue().get(key);
if(StringUtils.isBlank(oldValue) || System.currentTimeMillis() > Long.valueOf(oldValue)){
String result = redisTemplate.opsForValue().getAndSet(key,
String.valueOf(System.currentTimeMillis() + duration));
if(StringUtils.isBlank(result) || (StringUtils.isNotBlank(result) && StringUtils.equals(oldValue, result))){
redisTemplate.expire(key, duration, TimeUnit.MILLISECONDS);
success = true;
}
}
}
return success;
}
@SuppressWarnings("all")
public static boolean unlock(String key){
key = REDIS_LOCK_KEY_PREFIX + key;
return redisTemplate.delete(key);
}
}
SpringContextHolder
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author lijiayin
*/
@Component
public class SpringContextHolder implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringContextHolder.applicationContext = applicationContext;
}
@SuppressWarnings("all")
public static <T> T getBean(String beanName){
return (T)applicationContext.getBean(beanName);
}
public static <T> T getBean(Class<T> clazz){
return applicationContext.getBean(clazz);
}
public static <T> T getBean(String beanName, Class<T> clazz){
return applicationContext.getBean(beanName, clazz);
}
}
网友评论