前言
异步/非阻塞编程模型需要非阻塞API才能获得Redis连接。阻塞的连接池很容易导致阻塞事件循环并阻止您的应用程序进行处理的状态。Lettuce带有异步,非阻塞池实现,可与Lettuces异步连接方法一起使用。它不需要其他依赖项。Lettuce提供异步连接池支持。它需要一个Supplier
用于异步连接到任何受支持类型的连接。AsyncConnectionPoolSupport
将创建BoundedAsyncPool
。池可以分配包装的或直接的连接。
Jar引入
// redis
implementation 'io.lettuce:lettuce-core:5.2.2.RELEASE'
implementation 'org.apache.commons:commons-pool2:2.8.0'
基本使用
RedisClient client = RedisClient.create();
// 创建异步连接池
AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport.createBoundedObjectPool(
() -> client.connectAsync(StringCodec.UTF8, RedisURI.create(host, port)),
// 使用默认的连接池配置
BoundedPoolConfig.create());
// 从连接池中获取连接
CompletableFuture<StatefulRedisConnection<String, String>> con = pool.acquire();
// 异步执行setex命令并返回结果
CompletionStage<String> result = con.thenCompose(connection -> connection.async().setex("test", 30, "test")
// 释放连接池获取的连接
.whenComplete((s, throwable) -> pool.release(connection)));
// 关闭连接池
pool.closeAsync();
// 关闭client
client.shutdownAsync();
cluster使用
创建redis的Host和port数据类
public class RedisNode {
private String node;
private int port;
// 下面省略set,get和构造函数
}
初始化client和连接池
public class redisClusterAsyncPool {
// ClientResources should only be created once per app
private val clientResources = DefaultClientResources.create()
private void initclusterPool {
// 初始化redis cluster RedisURI
List<RedisURI> nodes = new ArrayList<>();
redisNodes.forEach(node -> {
nodes.add(
RedisURI.builder()
.withHost(node.getHost())
.withPort(node.getPort())
.withTimeout(Duration.ofMillis(timeOut))
.withPassword(password)
.build()
);
});
// 初始化redis cluster client
RedisClusterClient clusterClient =
RedisClusterClient.create(clientResources, nodes)
// 设置failover(集群故障转移)时的集群topology刷新机制
ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
.enableAdaptiveRefreshTrigger(
// Refresh cluster topology when Redis responds with a MOVED redirection
ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT,
// Refresh cluster topology when Redis Connections to a particular host run into
// persistent reconnects (more than one attempt).
ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS
)
// Set the timeout for adaptive topology updates.
.adaptiveRefreshTriggersTimeout(Duration.ofMinutes(3))
.build();
// Set the ClusterClientOptions for the client.
clusterClient.setOptions(
// Sets the ClusterTopologyRefreshOptions for detailed control of topology updates.
ClusterClientOptions.builder()
.topologyRefreshOptions(topologyRefreshOptions)
.autoReconnect(true) // set auto reconnection: true
.pingBeforeActivateConnection(true)
.build()
)
// 初始化cluster partitions,如果不初始化,在从连接吃获取连接的时会抛异常
clusterClient.partitions
// 初始化连接池配置
BoundedAsyncPool<StatefulRedisClusterConnection<String, String>> pool = AsyncConnectionPoolSupport.createBoundedObjectPool(
{ redisCluster?.connectAsync(StringCodec.UTF8) },
BoundedPoolConfig.builder()
.maxIdle(poolConfig.maxIdle)
.maxTotal(poolConfig.maxTotal)
.minIdle(poolConfig.minIdle)
.build()
)
// 从连接池中获取连接
CompletableFuture<StatefulRedisClusterConnection<String, String>> con = pool.acquire();
// 使用方法和基本使用一样
// ...
}
}