Redisson实现分布式锁
lock()上锁解析:
1,hexist判断redis是否有这个锁
2,hset设置锁,hash类型,key为锁名字,value是一对kv,k是当前redisson1的id,v为计数器,表示当前锁持有次数,也就是可重入锁。
3,设置锁默认生存时间为30s
4,采用看门狗策略,开启定时任务每隔10s去检查redisson1所持有的锁是否需要续期,每次续期30s
unlock()解锁解析:
1,unlock时会将计数器-1
2,当计数器=0时,会触发del操作,删除这个锁。
1,配置类初始化Redisson
@Configuration
public class RedisConfig {
@Bean
public Redisson redisson(){
//单机模式
Config config = new Config();
config.useSingleServer().setAddress("ip:port").setDatabase(0);
return (Redisson)Redisson.create(config);
}
}
2,get方法中使用redis分布式锁解决缓存击穿问题
public Product get(Long productId){
String productCacheKey = RedisKeyPrefixConst.PRODUCT_CACHE+ productId;
Product product = getProductFromCache(productCacheKey);
if(product != null){
return product;
}
//加锁
RLock lock = null;
try {
lock = redisson.getLock(productCacheKey);
lock.lock();
//双重检测解决缓存击穿问题,当热点缓存失效时,使用分布式锁重新设置缓存
product = getProductFromCache(productCacheKey);
if(product!= null){
return product;
}
//有双写不一致问题,在双写不一致问题处解决
Product product1 = iProductMapper.selectById(productId);
if(product1!=null){
//重新设置redis缓存
redisUtils.set(productCacheKey, product1, AuthConstant.EXPIRATION_TIME_IN_SECOND, TimeUnit.SECONDS);
}else {
redisUtils.set(productCacheKey, RedisKeyPrefixConst.PRODUCT_EMPTY_CACHE, AuthConstant.EXPIRATION_TIME_IN_SECOND, TimeUnit.SECONDS);
}
} finally {
lock.unlock();
}
return product;
}
private Product getProductFromCache(String productCacheKey) {
Product product = null;
Object o = redisUtils.get(productCacheKey);
if (o!= null){
if(StringUtils.equals(RedisKeyPrefixConst.PRODUCT_EMPTY_CACHE,o.toString())){
return new Product();
}
product = (Product)o;
}
return product;
}
public class RedisKeyPrefixConst {
public final static String PRODUCT_CACHE = "product:id";
public final static String PRODUCT_EMPTY_CACHE = "{}";
}
Redis红锁
在Redis的分布式环境中,我们假设有5个Redis master。这些节点完全互相独立,没有主从关系,5个redisson去获取锁,比如执行hset()设置key是lock_name,value中小key是redisson_id redis服务器的id,v是计数器,用于记录锁重入次数。
- 类似选举投票的机制,设置获取锁时间,和锁持有时间,当超过半数获取锁成功,表示这个锁获取成功。
- 释放锁时,锁的重入次数-1,如果等于0,就删除当前锁。如果>0说明锁重入了很多次,只-1不,不删除锁。
- 如果出现异常当超过锁过期时间时,直接删除锁。
1,注册红锁的RedissonClient
@Component
public class RedisConfig {
@Bean(name = "redissonRed1")
@Primary
public RedissonClient redissonRed1(){
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6379").setDatabase(0);
return Redisson.create(config);
}
@Bean(name = "redissonRed2")
public RedissonClient redissonRed2(){
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6380").setDatabase(0);
return Redisson.create(config);
}
@Bean(name = "redissonRed3")
public RedissonClient redissonRed3(){
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6381").setDatabase(0);
return Redisson.create(config);
}
@Bean(name = "redissonRed4")
public RedissonClient redissonRed4(){
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6382").setDatabase(0);
return Redisson.create(config);
}
@Bean(name = "redissonRed5")
public RedissonClient redissonRed5(){
Config config = new Config();
config.useSingleServer().setAddress("127.0.0.1:6383").setDatabase(0);
return Redisson.create(config);
}
}
红锁使用
@Service
public class GrabRedisRedissonRedLockLockServiceImpl implements GrabService {
// 红锁
@Autowired
@Qualifier("redissonRed1")
private RedissonClient redissonRed1;
@Autowired
@Qualifier("redissonRed2")
private RedissonClient redissonRed2;
@Autowired
@Qualifier("redissonRed3")
private RedissonClient redissonRed3;
@Autowired
@Qualifier("redissonRed4")
private RedissonClient redissonRed4;
@Autowired
@Qualifier("redissonRed5")
private RedissonClient redissonRed5;
@Autowired
OrderService orderService;
@Override
public String grabOrder(int orderId , int driverId){
System.out.println("红锁实现类");
//生成key
String lockKey = ("" + orderId).intern();
//redisson锁 单节点
//RLock rLock = redissonRed1.getLock(lockKey);
//红锁 redis son
RLock rLock1 = redissonRed1.getLock(lockKey);
RLock rLock2 = redissonRed2.getLock(lockKey);
RLock rLock3 = redissonRed3.getLock(lockKey);
RLock rLock4 = redissonRed4.getLock(lockKey);
RLock rLock5 = redissonRed5.getLock(lockKey);
RedissonRedLock rLock = new RedissonRedLock(rLock1,rLock2,rLock3,rLock4,rLock5);
try {
/**红锁
* waitTimeout 尝试获取锁的最大等待时间,超过这个值,则认为获取锁失败
* leaseTime 锁的持有时间,超过这个时间锁会自动失效(值应设置为大于业务处理的时间,确保在锁有效期内业务能处理完)
*/
boolean b1 = rLock.tryLock((long)waitTimeout, (long)leaseTime, TimeUnit.SECONDS);
if (b1){
System.out.println("加锁成功");
// 此代码默认 设置key 超时时间30秒,过10秒,再延时
System.out.println("司机:"+driverId+" 执行抢单逻辑");
boolean b = orderService.grab(orderId, driverId);
if(b) {
System.out.println("司机:"+driverId+" 抢单成功");
}else {
System.out.println("司机:"+driverId+" 抢单失败");
}
System.out.println("加锁成功");
}else {
System.out.println("加锁失败");
}
} finally {
rLock.unlock();
}
return null;
}
}