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

闭锁

使用场景:放假锁门

相关推荐
AAA修煤气灶刘哥1 天前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
christine-rr2 天前
linux常用命令(4)——压缩命令
linux·服务器·redis
凯子坚持 c2 天前
精通 Redis list:使用 redis-plus-plus 的现代 C++ 实践深度解析
c++·redis·list
weixin_456904272 天前
跨域(CORS)和缓存中间件(Redis)深度解析
redis·缓存·中间件
波波烤鸭2 天前
Redis 高可用实战源码解析(Sentinel + Cluster 整合应用)
数据库·redis·sentinel
MarkHard1232 天前
如何利用redis使用一个滑动窗口限流
数据库·redis·缓存
island13142 天前
【Redis#10】渐进式遍历 | 数据库管理 | redis_cli | RES
数据库·redis·bootstrap
心想事成的幸运大王2 天前
Redis的过期策略
数据库·redis·缓存
wuyunhang1234563 天前
Redis---集群模式
数据库·redis·缓存
Seven973 天前
Redis是如何进行内存管理的?缓存中有哪些常见问题?如何实现分布式锁?
redis