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";
    }

闭锁

使用场景:放假锁门

相关推荐
vivo互联网技术5 小时前
Redis key 消失之谜
数据库·redis·内存淘汰策略·redis抓包分析·机制分析
JosieBook5 小时前
【SpringBoot】29 核心功能 - 数据访问 - Spring Boot 2 操作 Redis 实践指南:本地安装与阿里云 Redis 对比应用
spring boot·redis·阿里云
青鱼入云10 小时前
redisson介绍
redis·1024程序员节
哲Zheᗜe༘14 小时前
了解学习Redis主从复制
数据库·redis·学习
一条懒鱼66616 小时前
Redis Sentinel哨兵集群
数据库·redis·sentinel
Zhu_S W17 小时前
Redis跳表:高效有序数据结构的深度剖析
数据结构·数据库·redis
初学者_xuan19 小时前
零基础新手小白快速了解掌握服务集群与自动化运维(十五)Redis模块-哨兵集群
运维·redis·自动化
weixin_4454766821 小时前
Vue+redis全局添加水印解决方案
前端·vue.js·redis
Deamon Tree1 天前
Redis的过期策略以及内存淘汰机制
java·数据库·redis·缓存
fouryears_234171 天前
Redis缓存更新策略
java·spring boot·redis·spring