【分布式锁】基于Redisson的分布式锁实现

发布于:2024-08-23 ⋅ 阅读:(56) ⋅ 点赞:(0)
以下代码是基于Redisson的分布式锁实现

yml文件中配置redis

# Spring配置
spring:
    # redis 配置
  redis:
    host: 127.0.0.1
    database: 1
    password:
    port: 6379
    address: redis://127.0.0.1:6379

编写配置类,注册redisClinet


/**
 * @description Redisson配置
 */
@Configuration
public class RedissonConfig {

    @Value("${spring.redis.address}")
    private String redisAddress;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.database}")
    private int database;

    @Bean(name = "redissonClient")
    public RedissonClient singleRedissonClient() {
        Config config = new Config();
        SingleServerConfig singleServerConfig = config.useSingleServer();
        singleServerConfig.setAddress(redisAddress).setDatabase(database);
        if (!StringUtils.isEmpty(password)) {
            singleServerConfig.setPassword(password);
        }
        return Redisson.create(config);
    }
}

编写分布式锁-接口 方便扩展



import com.ruoyi.common.lock.DistributedLock;

/**
 * @description 分布式锁工程接口
 */
public interface DistributedLockFactory {

    /**
     * 根据key获取分布式锁
     */
    DistributedLock getDistributedLock(String key);
}

编写实现类

import com.ruoyi.common.lock.DistributedLock;
import com.ruoyi.common.lock.factory.DistributedLockFactory;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @description 基于Redisson的分布式锁实现
 */
@Component
public class RedissonLockFactory implements DistributedLockFactory {
    private final Logger logger = LoggerFactory.getLogger(RedissonLockFactory.class);

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public DistributedLock getDistributedLock(String key) {
        RLock rLock = redissonClient.getLock(key);
        return new DistributedLock() {
            @Override
            public boolean tryLock(long waitTime, long leaseTime, TimeUnit unit) throws InterruptedException {
                boolean isLockSuccess = rLock.tryLock(waitTime, leaseTime, unit);
                logger.info("waitTime-leaseTime | {} get lock result:{}", key, isLockSuccess);
                return isLockSuccess;
            }

            @Override
            public boolean tryLock(long waitTime, TimeUnit unit) throws InterruptedException {
                boolean b = rLock.tryLock(waitTime, unit);
                logger.info("waitTime | {} get lock result:{}", key, b);
                return b;
            }

            @Override
            public boolean tryLock() throws InterruptedException {
                return rLock.tryLock();
            }

            @Override
            public void lock(long leaseTime, TimeUnit unit) {
                rLock.lock(leaseTime, unit);
            }

            @Override
            public void unlock() {
                if (isLocked() && isHeldByCurrentThread()) {
                    rLock.unlock();
                }
            }

            @Override
            public boolean isLocked() {
                return rLock.isLocked();
            }

            @Override
            public boolean isHeldByThread(long threadId) {
                return rLock.isHeldByThread(threadId);
            }

            @Override
            public boolean isHeldByCurrentThread() {
                return rLock.isHeldByCurrentThread();
            }
        };
    }
}

用法

DistributedLock distributedLock = distributedLockFactory.getDistributedLock(String.format("invoice_methods_lock_key_" + file.getName()));
  boolean b = distributedLock.tryLock(5, TimeUnit.SECONDS);
  if(b){
  	//执行具体逻辑
  }
//释放锁
 distributedLock.unlock();