分布式锁(五)——基于redisson的分布式锁实例

Redisson简介

Redisson是一个在Redis的基础上实现的Java驻内存数据网格(In-Memory Data Grid)。它不仅提供了一系列的分布式的Java常用对象,还提供了许多分布式服务。redisson参考文档。一定程度上他丰富了redis的数据类型 ,同时底层采用NIO的网络交互方式,进一步提升了分布式协调的相关能力。

更多关于Redisson的内容可以参见上述贴出的文档地址。Redisson实现分布式锁相比redis就方便了许多。

springboot中引入Redisson

1、引入redisson的配置

spring.redisson.address=redis://127.0.0.1:6379

配置需要以redis开头,毕竟在redisson的create源码中有这一段

public static URI create(String uri) {
    URI u = URI.create(uri);
    // Let's assuming most of the time it is OK.
    if (u.getHost() != null) {
        return u;
    }
    String s = uri.substring(0, uri.lastIndexOf(":")).replaceFirst("redis://", "").replaceFirst("rediss://", "");
    // Assuming this is an IPv6 format, other situations will be handled by
    // Netty at a later stage.
    return URI.create(uri.replace(s, "[" + s + "]"));
}

很明显的看到这里的字符串处理的时候,会切割掉redis开头或者rediss开头,如果没有则会抛出异常。

2、将redisson交给容器管理

/**
 * redisson的分布式客户端
 * @return
 */
@Bean
public RedissonClient redissonClient(){
    Config config = new Config();
    config.useSingleServer().setAddress(env.getProperty("spring.redisson.address"));
    RedissonClient client = Redisson.create(config);
    return client;
}

将这个bean交给有configuration注解的类进行托管。并返回RedissonClient(其实可以直接返回Redisson)

引入redisson,封装各种操作

package com.learn.lockservce.component;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * autor:liman
 * createtime:2020/1/30
 * comment: Redisson的分布式锁组件。
 */
@Component
@Slf4j
public class RedissonLockComponent implements InitializingBean {

    @Autowired
    private RedissonClient redissonClient;

    private static Redisson redisson;

    //注入后的属性设置方法,这里其实有点稍微多此一举,可以直接在容器托管的时候就返回Redisson就行。
    public void afterPropertiesSet() throws Exception {
        redisson = (Redisson) redissonClient;
    }

    /**
     * 获取锁
     * @param lockName
     * @return
     */
    public RLock acquireLock(String lockName){
        RLock lock = redisson.getLock(lockName);
        lock.lock();
        return lock;
    }

    /**
     * 释放锁
     * @param lock
     */
    public void releaseLock(RLock lock){
        lock.unlock();
    }
}

这里封装了获取锁和释放锁的操作,同时通过实现InitializingBean接口中的afterProperties的方法,完成了类型的强行转换。这里再顺带提一下,源码中可以看到Redisson是RedissonClient的一种实现。

分布式锁(五)——基于redisson的分布式锁实例

同样的业务处理

/**
 * 基于Redisson分布式锁
 * @param productLockDto
 * @return
 */
@Transactional(rollbackFor = Exception.class)
public int updateStockRedisson(ProductLockDto productLockDto){
    int res = 0;
    boolean flag = true;
    while(flag){
		//获取分布式锁。
        RLock rLock = redissonLockComponent.acquireLock(String.valueOf(productLockDto.getId()));
        try{
            if(rLock!=null){
				//真正的业务处理
                flag=false;
                ProductLock productLockEntity = lockMapper.selectByPrimaryKey(productLockDto.getId());
                int leftStock = productLockEntity.getStock();
                if(productLockEntity!=null && productLockEntity.getStock().compareTo(productLockDto.getStock())>=0){
                    productLockEntity.setStock(productLockDto.getStock());
                    res = lockMapper.updateStockForNegative(productLockEntity);
                    if(res>0){
                        log.info("基于redisson获取分布式锁成功,剩余stock:{}",leftStock-1);
                    }
                }
            }
        }catch (Exception e){
			//异常处理之后,继续获取锁
            log.error("获取锁异常,{}",e.fillInStackTrace());
            flag=true;
        }finally {
			//正确释放锁
            if(rLock!=null){
                redissonLockComponent.releaseLock(rLock);
                flag=false;
            }
        }
    }
    return res;
}

和之前几篇博客,一样的业务逻辑,一样的代码主体,一样的思想,这里就不总结了,似乎可以看出大体上都是这样的*

/**
 * 基于Redisson分布式锁
 * @param productLockDto
 * @return
 */
@Transactional(rollbackFor = Exception.class)
public int updateStockRedisson(ProductLockDto productLockDto){
    int res = 0;
    boolean flag = true;
    while(flag){
		//获取分布式锁。
        RLock rLock = redissonLockComponent.acquireLock(String.valueOf(productLockDto.getId()));
        try{
            if(rLock!=null){
				//真正的业务处理
                
            }
        }catch (Exception e){
			//异常处理之后,继续获取锁
            log.error("获取锁异常,{}",e.fillInStackTrace());
            flag=true;
        }finally {
			//正确释放锁
            
        }
    }
    return res;
}

总结

至此,关于几种分布式锁的简单实例,总结完成,具体参见如下:

分布式锁(一)——实例基本环境搭建

分布式锁(二)——基于数据库的分布式锁实例

分布式锁(三)——基于redis的分布式锁实例

分布式锁(四)——基于zookeeper的分布式锁实例

分布式锁(五)——基于redisson的分布式锁实例分布式锁(五)——基于redisson的分布式锁实例 谜一样的Coder 发布了125 篇原创文章 · 获赞 35 · 访问量 8万+ 私信 关注
上一篇:分布式锁之Redisson入门


下一篇:redis面试题