Redisson获取分布式锁

1. maven

<!-- redisson 分布式锁 -->
  <dependency>
      <groupId>org.redisson</groupId>
      <artifactId>redisson</artifactId>
      <version>3.11.2</version>
</dependency>

2. redisson客户端配置类

package com.harara.redis;

import com.montnets.common.util.StringUtil;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @author: harara
 * @date: 2019-11-05 19:58
 * @description:  redisson客户端配置类
 * @version: 1.0
 */
@Configuration
@Component
public class RedissonManager {

    /**redis集群节点*/
    private String cluster;

    /**redis密码*/
    private String password;

    /**redis 单节点ip*/
    private String host;

    /**redis单节点端口*/
    private String port;

    /**最大连接数*/
    private int maxPoolSize;


    @Bean
    public RedissonClient getRedissonClient(){
        return loadRedisson();
    }


    public RedissonClient loadRedisson(){
        RedissonClient client = null;
        Config config = new Config();
        //单节点
        if (!StringUtil.isEmpty(host)) {
            config.useSingleServer().
                    setAddress("redis://" + host + ":" + port)
//                    .setPassword(password)
                    .setConnectionPoolSize(maxPoolSize)
                    //最小空闲连接
                    .setConnectionMinimumIdleSize(0);
            //如果密码不为空,设置密码
            if(!StringUtil.isEmpty(password)){
                config.useSingleServer().setPassword(password);
            }
            client = Redisson.create(config);
        } else {
            //集群节点
            String[] nodes = cluster.split(",");
            //redisson版本是3.5,集群的ip前面要加上“redis://”,不然会报错,3.2版本可不加
            for (int i = 0; i < nodes.length; i++) {
                nodes[i] = "redis://" + nodes[i];
            }
            //这是用的集群server
            config.useClusterServers()
                    //设置集群状态扫描时间2000
                    .setScanInterval(2000)
                    .addNodeAddress(nodes)
//                    .setPassword(password)
                    .setMasterConnectionPoolSize(maxPoolSize)
                    //最小空闲连接
                    .setMasterConnectionMinimumIdleSize(0);
            //如果密码不为空,设置集群密码
            if (!StringUtil.isEmpty(password)) {
                config.useClusterServers().setPassword(password);
            }
            client = Redisson.create(config);
//            System.out.println(config.);
            //可通过打印redisson.getConfig().toJSON().toString()来检测是否配置成功
        }
        return client;
    }
}

3.获取锁类(加锁,解锁)

package com.montnets.ums.msgroute.redis;

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

import java.util.concurrent.TimeUnit;

/**
 * @author: chenly
 * @date: 2019-11-05 20:29
 * @description: 获取redisson分布式锁类
 * @version: 1.0
 */
@Component
@Slf4j
public class RedissonDistributedLocker {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * lock(),拿不到lock就不罢休,不然线程就一直block
     * @param lockKey
     * @return
     */
    public RLock lock(String lockKey){
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
        return lock;
    }

    /**
     * leaseTime为加锁时间,单位为秒
     * @param lockKey  锁的名称
     * @param leaseTime 加锁时间,单位秒
     * @return
     */
    public RLock lock(String lockKey,long leaseTime){
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
        return lock;
    }

    /**
     * leaseTime为加锁时间,单位为秒
     * @param lockKey 锁的名称
     * @param unit  时间单位
     * @param leaseTime  加锁时间
     * @return
     */
    public RLock lock(String lockKey,TimeUnit unit,long leaseTime){
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime,unit);
        return lock;
    }


    /**
     * 加锁
     * tryLock(),马上返回,拿到lock就返回true,不然返回false。
     * 带时间限制的tryLock(),拿不到lock,就等一段时间,超时返回false.
     * @param lockKey 锁的名称
     * @param unit   单位名称
     * @param waitTime  等待时间
     * @param leaseTime 加锁时间
     * @return
     */
    public boolean tryLock(String lockKey,TimeUnit unit,long waitTime,long leaseTime){
        RLock lock = redissonClient.getLock(lockKey);
        try{
            lock.tryLock(waitTime,leaseTime,unit);
            return true;
        }catch (InterruptedException e){
            return false;
        }
    }

    /**
     *
     * 带时间限制的tryLock(),拿不到lock,就等一段时间,超时返回false.
     * @param lockKey
     * @param waitTime
     * @return
     */
    public boolean tryLock(String lockKey,long waitTime,TimeUnit unit){
        RLock rLock = redissonClient.getLock(lockKey);
        try{
            rLock.tryLock(waitTime,unit);
            return true;
        }catch (InterruptedException e){
            return false;
        }
    }

    /**
     * 解锁
     * @param lockKey  锁的名称
     */
    public void unlock(String lockKey){
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

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

相关推荐