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

闭锁

使用场景:放假锁门

相关推荐
爱上语文37 分钟前
Redis基础(4):Set类型和SortedSet类型
java·数据库·redis·后端
软件2054 小时前
【redis使用场景——缓存——数据淘汰策略】
数据库·redis·缓存
加勒比海涛5 小时前
Spring Cloud Gateway 实战:从网关搭建到过滤器与跨域解决方案
数据库·redis·缓存
大只鹅7 小时前
分布式部署下如何做接口防抖---使用分布式锁
redis·分布式
MonkeyKing_sunyuhua11 小时前
Ehcache、Caffeine、Spring Cache、Redis、J2Cache、Memcached 和 Guava Cache 的主要区别
redis·spring·memcached
笨手笨脚の10 天前
Redis 源码分析-Redis 中的事件驱动
数据库·redis·缓存·select·nio·epoll·io模型
(:满天星:)10 天前
Redis哨兵模式深度解析与实战部署
linux·服务器·网络·数据库·redis·缓存·centos
weixin_4383354010 天前
Spring Boot:运用Redis统计用户在线数量
java·spring boot·redis
十六点五10 天前
Redis(2)——AOF持久化
java·redis·后端
编程乐学(Arfan开发工程师)10 天前
75、单元测试-嵌套测试
前端·javascript·redis·python·单元测试·bootstrap