记一次Redisson分布式锁实践

背景

在分布式架构服务系统中,分布式锁是一种处理幂等的有效方式,记录一下生产级Redisson的使用方式。

SpringBoot引入

    <dependency>
        <groupId>org.redisson</groupId>
        <artifactId>redisson-spring-boot-starter</artifactId>
        <version>3.17.1</version>
    </dependency>

配置application配置文件

配置redis的连接信息

redisson 的使用流程

@RestController
@RequestMapping("/redisson")
@AllArgsConstructor
public class RedissonController {

    private final RedissonClient redissonClient;

    @GetMapping("/test")
    public String test() {
        // 生成一把锁,锁的生成要结合业务场景,为单笔业务交易设置一个KEY,通过业务KEY来生成锁
        RLock lock = redissonClient.getLock("test");
        boolean isLock;
        try {
            // 尝试加锁,最多等待1秒,上锁以后10秒自动解锁
            // 这个等待时间和自动解锁时间需根据业务做相应的调整
            isLock = lock.tryLock(1, 10, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            return "加锁失败,";
        }
        try {
            if (!isLock) {
                return "未获取到锁";
            }
            // 获取到锁,业务逻辑处理
            try {
                Thread.sleep(8000);
            } catch (InterruptedException e) {
                return "业务处理异常";
            }
        } finally {
            if (lock != null && lock.isHeldByCurrentThread()) {
                // 释放锁
                lock.unlockAsync();
            }
        }
        return "ok";
    }
}

posted on   bigstrong_code  阅读(98)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· 单线程的Redis速度为什么快?
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示