1. 概述

Redisson 是一个功能强大的 Java Redis 客户端库。本文将深入探索其核心特性,并展示如何利用它简化分布式业务系统的开发。

Redisson 本质上是一个基于 Redis 的内存数据网格,它提供了分布式 Java 对象和服务。其分布式内存数据模型支持跨应用和服务器的领域对象与服务共享。

本文将涵盖 Redisson 的配置方式、运行原理,并重点介绍其核心对象和服务。

2. Maven 依赖

首先在 pom.xml 中添加 Redisson 依赖:

<dependency>
    <groupId>org.redisson</groupId>
    <artifactId>redisson</artifactId>
    <version>3.20.0</version>
</dependency>

最新版本可在此处查看:Maven Central

3. 配置

开始前请确保已安装并运行最新版 Redis:

Redisson 支持多种 Redis 架构:

  • ✅ 单节点
  • ✅ 主从节点
  • ✅ 哨兵节点
  • ✅ 集群节点
  • ✅ 复制节点

⚠️ 特别支持 AWS ElastiCache 和 Azure Redis Cache 的集群/复制模式

3.1. 基础连接

连接本地默认端口(6379)的 Redis:

RedissonClient client = Redisson.create();

3.2. Java 配置

通过 Java 代码自定义配置:

Config config = new Config();
config.useSingleServer()
  .setAddress("redis://127.0.0.1:6379");

RedissonClient client = Redisson.create(config);

关键配置项说明:

  • setAddress():指定 Redis 节点地址
  • retryAttempts:重试次数
  • connectionTimeout:连接超时
  • clientName:客户端标识

其他架构配置方法: | 架构类型 | 配置方法 | 参考文档 | |---------|---------|---------| | 单节点 | useSingleServer() | 配置说明 | | 主从节点 | useMasterSlaveServers() | 配置说明 | | 哨兵节点 | useSentinelServers() | 配置说明 | | 集群节点 | useClusterServers() | 配置说明 | | 复制节点 | useReplicatedServers() | 配置说明 |

3.3. 文件配置

支持从 JSON/YAML 文件加载配置:

Config config = Config.fromJSON(new File("singleNodeConfig.json"));  
RedissonClient client = Redisson.create(config);

JSON 配置示例 (singleNodeConfig.json):

{
    "singleServerConfig": {
        "idleConnectionTimeout": 10000,
        "connectTimeout": 10000,
        "timeout": 3000,
        "retryAttempts": 3,
        "retryInterval": 1500,
        "password": null,
        "subscriptionsPerConnection": 5,
        "clientName": null,
        "address": "redis://127.0.0.1:6379",
        "subscriptionConnectionMinimumIdleSize": 1,
        "subscriptionConnectionPoolSize": 50,
        "connectionMinimumIdleSize": 10,
        "connectionPoolSize": 64,
        "database": 0,
        "dnsMonitoringInterval": 5000
    },
    "threads": 0,
    "nettyThreads": 0,
    "codec": null
}

YAML 配置示例:

singleServerConfig:
    idleConnectionTimeout: 10000
    connectTimeout: 10000
    timeout: 3000
    retryAttempts: 3
    retryInterval: 1500
    password: null
    subscriptionsPerConnection: 5
    clientName: null
    address: "redis://127.0.0.1:6379"
    subscriptionConnectionMinimumIdleSize: 1
    subscriptionConnectionPoolSize: 50
    connectionMinimumIdleSize: 10
    connectionPoolSize: 64
    database: 0
    dnsMonitoringInterval: 5000
threads: 0
nettyThreads: 0
codec: !<org.redisson.codec.JsonJacksonCodec> {}

💡 提示:可通过 config.toJSON()/config.toYAML() 将 Java 配置导出为文件

4. 操作模式

Redisson 支持三种操作接口:

  • ✅ 同步接口
  • ✅ 异步接口
  • ✅ 响应式接口

所有实体(对象、集合、锁、服务)均提供同步和异步方法,且线程安全

4.1. 同步操作

RedissonClient client = Redisson.create();
RAtomicLong myLong = client.getAtomicLong('myLong');

4.2. 异步操作

异步方法名以 Async 结尾,返回 RFuture 对象:

RFuture<Boolean> isSet = myLong.compareAndSetAsync(6, 27);
isSet.handle((result, exception) -> {
    // 处理结果或异常
});

4.3. 响应式操作

基于 Reactive Streams 标准:

RedissonReactiveClient client = Redisson.createReactive();
RAtomicLongReactive myLong = client.getAtomicLong("myLong");
Publisher<Boolean> isSetPublisher = myLong.compareAndSet(5, 28);

5. 分布式对象

Redisson 对象会被序列化并存储在 Redis 节点中,支持跨应用/服务器共享。核心特性:

  • ✅ 无锁线程安全
  • ✅ 原子操作
  • ✅ 数据一致性保障

5.1. 键管理

通过 RKeys 接口管理 Redis 键:

RKeys keys = client.getKeys();

// 获取所有键
Iterable<String> allKeys = keys.getKeys();

// 按模式匹配键
Iterable<String> keysByPattern = keys.getKeysByPattern('key*');

5.2. 核心对象类型

对象类型 描述 最大尺寸
ObjectHolder (RBucket) 任意类型对象 512MB
AtomicLong (RAtomicLong) 原子长整型 -
Topic (RTopic) 发布订阅机制 -
BitSet (RBitSet) 位集合 -
BloomFilter (RBloomFilter) 布隆过滤器 -

示例:ObjectHolder

RBucket<Ledger> bucket = client.getBucket("ledger");
bucket.set(new Ledger());
Ledger ledger = bucket.get();

示例:AtomicLong

RAtomicLong atomicLong = client.getAtomicLong("myAtomicLong");
atomicLong.set(5);
atomicLong.incrementAndGet();

示例:Topic

订阅消息:

RTopic subscribeTopic = client.getTopic("baeldung");
subscribeTopic.addListener(CustomMessage.class,
  (channel, customMessage) -> future.complete(customMessage.getMessage()));

发布消息:

RTopic publishTopic = client.getTopic("baeldung");
long clientsReceivedMessage = publishTopic.publish(new CustomMessage("This is a message"));

📚 更多对象参考:分布式对象文档

6. 分布式集合

Redisson 提供与 Java 集合框架兼容的分布式集合:

6.1. Map

实现 ConcurrentMapMap 接口,支持四种实现:

  • RMap:基础映射
  • RMapCache:支持过期淘汰
  • RLocalCachedMap:本地缓存增强
  • RClusteredMap:集群分片存储
RMap<String, Ledger> map = client.getMap("ledger");
Ledger newLedger = map.put("123", new Ledger());

6.2. Set

实现 Set 接口,三种实现:

  • RSet:基础集合
  • RSetCache:支持过期淘汰
  • RClusteredSet:集群分片存储
RSet<Ledger> ledgerSet = client.getSet("ledgerSet");
ledgerSet.add(new Ledger());

6.3. List

实现 List 接口:

RList<Ledger> ledgerList = client.getList("ledgerList");
ledgerList.add(new Ledger());

📚 更多集合参考:分布式集合文档

7. 分布式锁与同步器

Redisson 提供跨应用/服务器的线程同步机制:

7.1. 基础锁

实现 Lock 接口:

RLock lock = client.getLock("lock");
lock.lock();
try {
    // 执行长时操作...
} finally {
    lock.unlock();
}

7.2. 联锁

将多个锁组合为单一锁:

RLock lock1 = clientInstance1.getLock("lock1");
RLock lock2 = clientInstance2.getLock("lock2");
RLock lock3 = clientInstance3.getLock("lock3");

RedissonMultiLock multiLock = new RedissonMultiLock(lock1, lock2, lock3);
multiLock.lock();
try {
    // 执行长时操作...
} finally {
    multiLock.unlock();
}

其他同步器:

  • ReadWriteLock:读写锁
  • Semaphore:信号量
  • CountDownLatch:倒计时门闩

📚 更多锁机制参考:分布式锁文档

8. 分布式服务

8.1. 远程服务

基于 Redis 的 Java 远程方法调用:

服务端注册:

RRemoteService remoteService = client.getRemoteService();
remoteService.register(LedgerServiceInterface.class, new LedgerServiceImpl());

客户端调用:

RRemoteService remoteService = client.getRemoteService();
LedgerServiceInterface ledgerService = remoteService.get(LedgerServiceInterface.class);
List<String> entries = ledgerService.getEntries(10);

8.2. 实时对象服务

将标准 Java 对象扩展为跨 JVM 共享的增强对象:

定义实时对象:

@REntity
public class LedgerLiveObject {
    @RId
    private String name;
    // getters/setters...
}

使用实时对象:

RLiveObjectService service = client.getLiveObjectService();

// 持久化新对象
LedgerLiveObject ledger = new LedgerLiveObject();
ledger.setName("ledger1");
ledger = service.persist(ledger);

// 获取已存在对象
LedgerLiveObject existingLedger = service.get(LedgerLiveObject.class, "ledger1");

💡 核心机制:通过运行时代理将对象字段映射到 Redis Hash

9. 管道操作

支持批量原子操作:

RBatch batch = client.createBatch();
batch.getMap("ledgerMap").fastPutAsync("1", "2");
batch.getMap("ledgerMap").putAsync("2", "5");

BatchResult<?> batchResult = batch.execute();

10. 脚本执行

支持原生 LUA 脚本:

client.getBucket("foo").set("bar");
String result = client.getScript().eval(Mode.READ_ONLY,
  "return redis.call('get', 'foo')", RScript.ReturnType.VALUE);

11. 低级客户端

当需要执行 Redisson 未封装的原生命令时:

RedisClientConfig redisClientConfig = new RedisClientConfig();
redisClientConfig.setAddress("localhost", 6379);

RedisClient nativeClient = RedisClient.create(redisClientConfig);
RedisConnection conn = nativeClient.connect();

// 执行原生命令
conn.sync(StringCodec.INSTANCE, RedisCommands.SET, "test", 0);

conn.closeAsync();
nativeClient.shutdown();

12. 总结

本文深入探讨了 Redisson 的核心能力:

  • ✅ 分布式对象(原子操作/主题/位集合)
  • ✅ 分布式集合(映射/集合/列表)
  • ✅ 分布式锁(基础锁/联锁/读写锁)
  • ✅ 分布式服务(远程调用/实时对象)
  • ✅ 高级特性(管道/脚本/低级客户端)

Redisson 还提供与主流框架的集成:

  • JCache API
  • Spring Cache
  • Hibernate Cache
  • Spring Sessions

📚 集成文档参考:框架集成指南

完整代码示例请查看:GitHub 项目


原始标题:A Guide to Redis with Redisson