springboot 使用 Redisson 实现分布式锁

首先引入依赖 



    org.redisson
    redisson
    3.16.8

 然后配置redisson


import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import org.redisson.config.Config;
/**
 * @program: volunteer
 * @description:
 * @author: Ligh
 * @create: 2023-03-29 16:29
 **/
@Configuration
public class MyRedissonConfig {
    /**
     * 所有对Redisson的使用都是通过RedissonClient对象
     * @return
     */
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redissonClient(){
        // 创建配置 指定redis地址及节点信息
        Config config = new Config();
        config.useSingleServer().setAddress("redis://47.116.**.**:6379").setPassword("12345");

        // 根据config创建出RedissonClient实例
        RedissonClient redissonClient = Redisson.create(config);
        return redissonClient;
    }
}
    @Autowired
    private RedissonClient redissonClient;

    @GetMapping("/test")
    public AjaxResult test() {
        RLock phoneLock = redissonClient.getLock("123456Lock");
        // 具有Watch Dog 自动延期机制 默认续30s 每隔30/3=10 秒续到30s
        phoneLock.lock();
        //phoneLock.lock(3, TimeUnit.SECONDS);//没有Watch Dog ,3s后自动释放
        boolean a = false;
        try {
            Integer res = redisCache.getCacheObject("123456");
            if (res == 0) {
                a = true;
                return AjaxResult.error("库存已空");
            }
            System.out.println(res);
            redisCache.setCacheObject("123456", res - 1);
        } finally {
            if (a)
                System.out.println(1111);
            if (Objects.nonNull(phoneLock) && phoneLock.isLocked() && phoneLock.isHeldByCurrentThread()) {
                phoneLock.unlock();
            }
        }
        return AjaxResult.success();
    }

效果

springboot 使用 Redisson 实现分布式锁_第1张图片

private void redissonDoc() throws InterruptedException {
    //1. 普通的可重入锁
    RLock lock = redissonClient.getLock("generalLock");

    // 拿锁失败时会不停的重试
    // 具有Watch Dog 自动延期机制 默认续30s 每隔30/3=10 秒续到30s
    lock.lock();

    // 尝试拿锁10s后停止重试,返回false
    // 具有Watch Dog 自动延期机制 默认续30s
    boolean res1 = lock.tryLock(10, TimeUnit.SECONDS);

    // 拿锁失败时会不停的重试
    // 没有Watch Dog ,10s后自动释放
    lock.lock(10, TimeUnit.SECONDS);

    // 尝试拿锁100s后停止重试,返回false
    // 没有Watch Dog ,10s后自动释放
    boolean res2 = lock.tryLock(100, 10, TimeUnit.SECONDS);

    //2. 公平锁 保证 Redisson 客户端线程将以其请求的顺序获得锁
    RLock fairLock = redissonClient.getFairLock("fairLock");

    //3. 读写锁 没错与JDK中ReentrantLock的读写锁效果一样
    RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("readWriteLock");
    readWriteLock.readLock().lock();
    readWriteLock.writeLock().lock();
}

你可能感兴趣的:(spring,boot,redis,spring,boot,java,redis)