Redisson

整合 Redisson

1、引入依赖

xml 复制代码
<dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.12.0</version>
</dependency>

2、配置

java 复制代码
@Configuration
public class MyRedissonConfig {
    @Bean(destroyMethod = "shutdown")
    public RedissonClient redisson() {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://192.168.56.10:6379");
        return Redisson.create(config);
    }
}

3、使用

java 复制代码
	@Autowired
    private RedissonClient redissonClient;

    @GetMapping("/redisson")
    public String redisson() {
        RLock lock = redissonClient.getLock("my-lock");
        lock.lock();
        try {
            Thread.sleep(30000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
        return "redisson";
    }

Redisson 分布式锁的实现

1、实现了锁的自动续期。如果业务超长,运行期间自动给锁续上新的30s。

2、默认30s 后自动删除,不会产生死锁。

注意

1、 lock.lock(10, TimeUnit.SECONDS); 指定过期时间的加锁,不会有看门狗功能。

2、看门狗功能的实现原理:占锁成功后,会启动一个定时任务,每隔1/3看门狗时间,重置锁的过期时间。

读写锁

保证一定能读到最新数据,修改期间,写锁是排它锁,读锁是共享锁。

  • 读 + 读:相当于无锁
  • 写 + 读:等待写锁释放
  • 写 + 写:阻塞方式
  • 读 + 写:等待读锁释放

信号量

使用场景:车库停车、分布式限流

java 复制代码
 	@GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        boolean b = park.tryAcquire();
        return "ok->" + b;
    }

    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
        RSemaphore park = redissonClient.getSemaphore("park");
        park.release();
        return "ok";
    }

闭锁

使用场景:放假锁门

相关推荐
IT大白鼠1 天前
Redis 系列 · 第 01 篇——认知入门:Redis 是什么
redis·nosql
彧azz1 天前
Linux 环境下 Redis 学习总结:数据类型、持久化、锁、事务、主从与缓存问题
linux·redis·笔记·学习·面试
lbb 小魔仙1 天前
OpenClaw + cpolar 实战:远程 NAS、分享小游戏、RDP,再配置公网 AI 入口
数据库·人工智能·redis·oracle·prometheus
夕除1 天前
redis--018
redis
两锭子1 天前
Redis基础
redis
烟沙九洲1 天前
Redis 缓存穿透、缓存击穿、缓存雪崩
数据库·redis
字节探索1 天前
Redis 只会当缓存用?这 10 大实战场景,让你的系统快到飞起
redis·后端
于樱花森上飞舞1 天前
【Redis】哨兵详解
java·开发语言·数据库·redis
Rain的Java大神之路2 天前
如何快速上传10G文件
java·spring boot·redis·后端·mysql·spring cloud·面试
Wang's Blog2 天前
Java 接入Redis: 通用命令与键管理
java·服务器·redis