1. RedissonClient 核心功能与应用场景解析RedissonClient 是 Java 生态中操作 Redis 最强大的客户端之一它不仅仅是简单的 Redis 命令封装而是提供了分布式场景下的高阶抽象。我在电商秒杀系统和高并发IM系统中深度使用过这个工具实测单节点可支撑 2W TPS 的分布式锁操作。相比 Jedis 等基础客户端RedissonClient 的核心优势在于内置 30 种分布式对象和服务BitSet、BloomFilter、AtomicLong...支持 Reactive 编程模式完善的分布式锁实现支持锁续期、红锁算法与 Spring 生态无缝集成最典型的应用场景包括分布式锁控制秒杀库存扣减分布式集合操作全局去重集合延迟队列实现订单超时关闭分布式计数器UV统计重要提示生产环境建议使用最新稳定版当前为 3.23.2老版本存在锁泄漏风险2. 环境配置与基础使用2.1 依赖引入与连接配置Maven 配置示例建议锁定小版本dependency groupIdorg.redisson/groupId artifactIdredisson/artifactId version3.23.2/version /dependency单节点配置模板Config config new Config(); config.useSingleServer() .setAddress(redis://127.0.0.1:6379) .setPassword(yourpassword) .setDatabase(0) .setConnectionPoolSize(64) // 默认值64 .setConnectionMinimumIdleSize(24); // 默认值24 RedissonClient client Redisson.create(config);集群模式配置差异点config.useClusterServers() .addNodeAddress(redis://node1:6379, redis://node2:6379) .setScanInterval(2000); // 集群状态扫描间隔(ms)2.2 基础数据结构操作2.2.1 分布式Map使用示例RMapString, Object map client.getMap(userSession); map.put(user:1001, new UserSession(/*...*/)); map.expire(30, TimeUnit.MINUTES); // 设置TTL // 原子性更新 map.computeIfPresent(user:1001, (k, v) - { ((UserSession)v).updateLastActive(); return v; });2.2.2 分布式List特性RListString msgQueue client.getList(messageQueue); msgQueue.add(order:created:10086); // 支持双向操作 msgQueue.addFirst(high_priority_msg); String last msgQueue.removeLast();3. 分布式锁深度实践3.1 可重入锁标准写法RLock lock client.getLock(orderLock); try { // 尝试获取锁等待时间5秒锁自动释放时间30秒 if (lock.tryLock(5, 30, TimeUnit.SECONDS)) { // 业务逻辑 updateOrderStatus(orderId); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } finally { if (lock.isLocked() lock.isHeldByCurrentThread()) { lock.unlock(); } }关键参数说明等待时间避免线程长时间阻塞租约时间必须大于业务执行时间否则会出现并发问题必须校验锁归属防止误删其他线程的锁3.2 锁续期机制Redisson 的 WatchDog 机制会为未显式设置leaseTime的锁自动续期// 无leaseTime参数启用看门狗默认30秒续期 lock.lock(); // 显式设置leaseTime会禁用看门狗 lock.lock(10, TimeUnit.SECONDS);踩坑记录曾经因误用leaseTime导致库存超卖建议常规业务使用默认看门狗模式短任务可设leaseTime但要预留3倍安全余量必须捕获InterruptedException做线程中断标记4. 高级特性实战4.1 分布式限流器RRateLimiter rateLimiter client.getRateLimiter(apiLimit); // 每秒10个令牌桶容量50 rateLimiter.trySetRate(RateType.OVERALL, 10, 50, RateIntervalUnit.SECONDS); if (rateLimiter.tryAcquire()) { callExternalAPI(); } else { throw new RateLimitException(); }4.2 延迟队列实现RDelayedQueueString delayedQueue client.getDelayedQueue( client.getQueue(taskQueue) ); // 30秒后放入队列 delayedQueue.offer(taskId123, 30, TimeUnit.SECONDS); // 消费端 String task client.getQueue(taskQueue).poll(); if (task ! null) { processExpiredTask(task); }4.3 布隆过滤器应用RBloomFilterString bloomFilter client.getBloomFilter(userFilter); bloomFilter.tryInit(1000000L, 0.03); // 100万数据量3%误判率 // 用户注册时 if (!bloomFilter.contains(username)) { bloomFilter.add(username); createUser(username); } else { // 可能存在误判 checkUsernameConflict(username); }5. 性能优化与问题排查5.1 连接池配置黄金法则根据压测经验推荐配置比例| 并发量 | 建议poolSize | 建议minIdle | |--------|--------------|-------------| | 500 | 32 | 10 | | 500-2K | 64 | 20 | | 2K | 128 | 32 |关键调优参数idleConnectionTimeout默认10000msconnectTimeout默认10000mstimeout默认3000ms5.2 常见异常处理RedisTimeoutException检查网络延迟适当增加timeout参数监控Redis节点负载RedisConnectionException验证密码和防火墙设置检查连接池是否耗尽启用备用节点切换锁泄漏检测RLock lock client.getLock(resourceLock); System.out.println(lock.isLocked()); // 当前是否被锁 System.out.println(lock.getHoldCount()); // 重入次数5.3 监控集成方案通过JMX暴露关键指标RedissonNodeConfig nodeConfig new RedissonNodeConfig(config); nodeConfig.setExecutorServiceWorkers(2); RedissonNode node RedissonNode.create(nodeConfig); node.start(); // 通过JConsole查看 // org.redisson.connection.pool.active // org.redisson.connection.pool.idle6. Spring Boot 集成最佳实践6.1 自动化配置模板Configuration public class RedissonConfig { Value(${spring.redis.host}) private String host; Bean(destroyMethod shutdown) public RedissonClient redisson() { Config config new Config(); config.useSingleServer() .setAddress(redis:// host :6379) .setPingConnectionInterval(1000); return Redisson.create(config); } }6.2 分布式锁注解化自定义注解实现Target(ElementType.METHOD) Retention(RetentionPolicy.RUNTIME) public interface DistributedLock { String key(); long waitTime() default 5L; long leaseTime() default 30L; } Aspect Component public class LockAspect { Autowired private RedissonClient redisson; Around(annotation(lock)) public Object around(ProceedingJoinPoint pjp, DistributedLock lock) throws Throwable { RLock rLock redisson.getLock(lock.key()); try { if (rLock.tryLock(lock.waitTime(), lock.leaseTime(), TimeUnit.SECONDS)) { return pjp.proceed(); } throw new LockAcquireException(); } finally { if (rLock.isLocked() rLock.isHeldByCurrentThread()) { rLock.unlock(); } } } }使用示例DistributedLock(key order: #orderId) public void updateOrder(Long orderId) { // 业务逻辑 }7. 生产环境验证要点在金融级系统中落地时必须验证故障注入测试模拟Redis节点宕机网络分区测试长时间GC场景性能基准# 使用redis-benchmark对比 redis-benchmark -t set,get -n 100000数据一致性检查定期dump内存数据校验监控锁的持有时间分布记录异常锁释放日志压测建议参数config.setTransportMode(TransportMode.NIO) .setThreads(16) // 默认值16 .setNettyThreads(32); // 默认值32最后分享一个真实案例在某票务系统使用RedissonClient处理峰值10万QPS的选座请求时通过合理设置lockWatchdogTimeout调整为10秒和connectionPoolSize增至256成功将锁获取耗时从78ms降至12ms。关键是要根据实际业务特点调整参数不要盲目使用默认值。
阅读完成 · 觉得有帮助?