Redis Lettuce客户端异步连接池详解

前言

异步/非阻塞编程模型需要非阻塞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();
        // 使用方法和基本使用一样
        // ...
    }
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
下面是一个使用 Lettuce Redis 实现分布式锁的工具类,其中包含了防止被其他线程解锁的实现。 ```java import io.lettuce.core.RedisClient; import io.lettuce.core.api.StatefulRedisConnection; import io.lettuce.core.api.sync.RedisCommands; import io.lettuce.core.cluster.ClusterClientOptions; import io.lettuce.core.cluster.ClusterTopologyRefreshOptions; import io.lettuce.core.cluster.RedisClusterClient; import io.lettuce.core.cluster.api.StatefulRedisClusterConnection; import java.util.UUID; import java.util.concurrent.TimeUnit; public class RedisDistributedLock { private static final long DEFAULT_LOCK_EXPIRATION_TIME = 30000; private static final long DEFAULT_WAIT_TIMEOUT = 10000; private static final long DEFAULT_RETRY_INTERVAL = 200; private RedisCommands<String, String> redisCommands; private StatefulRedisConnection<String, String> redisConnection; private StatefulRedisClusterConnection<String, String> redisClusterConnection; private String lockKey; private String lockValue; private long lockExpirationTime; private long waitTimeout; private long retryInterval; private boolean isCluster; public RedisDistributedLock(String redisUrl, String lockKey) { this(redisUrl, lockKey, DEFAULT_LOCK_EXPIRATION_TIME, DEFAULT_WAIT_TIMEOUT, DEFAULT_RETRY_INTERVAL); } public RedisDistributedLock(String redisUrl, String lockKey, long lockExpirationTime, long waitTimeout, long retryInterval) { RedisClient redisClient; RedisClusterClient redisClusterClient; if (redisUrl.contains(",")) { redisClusterClient = RedisClusterClient.create(redisUrl); redisClusterClient.setOptions( ClusterClientOptions.builder() .topologyRefreshOptions( ClusterTopologyRefreshOptions.builder() .enablePeriodicRefresh() .enableAllAdaptiveRefreshTriggers() .refreshPeriod(Duration.ofSeconds(30)) .build()) .build()); this.redisClusterConnection = redisClusterClient.connect(); this.redisCommands = redisClusterConnection.sync(); this.isCluster = true; } else { redisClient = RedisClient.create(redisUrl); this.redisConnection = redisClient.connect(); this.redisCommands = redisConnection.sync(); this.isCluster = false; } this.lockKey = lockKey; this.lockExpirationTime = lockExpirationTime; this.waitTimeout = waitTimeout; this.retryInterval = retryInterval; this.lockValue = UUID.randomUUID().toString(); } public boolean acquireLock() { long startTime = System.currentTimeMillis(); while (true) { if (System.currentTimeMillis() - startTime > waitTimeout) { return false; } if (isCluster) { if (redisCommands.set(lockKey, lockValue, "NX", "PX", lockExpirationTime)) { return true; } } else { if (redisCommands.set(lockKey, lockValue, "NX", "PX", lockExpirationTime)) { return true; } } try { Thread.sleep(retryInterval); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } public void releaseLock() { if (isCluster) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " + "return redis.call('del', KEYS[1]) " + "else " + "return 0 " + "end"; redisCommands.eval(script, RedisCommands.<String, String>newScript().withResultType(String.class), new String[]{lockKey}, lockValue); } else { redisCommands.eval("if redis.call('get', KEYS[1]) == ARGV[1] then " + "return redis.call('del', KEYS[1]) " + "else " + "return 0 " + "end", RedisCommands.<String, String>newScript().withResultType(String.class), new String[]{lockKey}, lockValue); } } public boolean isCluster() { return isCluster; } public void close() { if (isCluster) { redisClusterConnection.close(); } else { redisConnection.close(); } } } ``` 使用示例: ```java public static void main(String[] args) { RedisDistributedLock lock = new RedisDistributedLock("redis://localhost:6379", "myLock"); if (lock.acquireLock()) { try { // do something } finally { lock.releaseLock(); } } lock.close(); } ``` 在 acquireLock() 方法中,使用了一个 while 循环来不断尝试获取锁,直到成功或者超时。在 releaseLock() 方法中,使用了 Redis 的 Lua 脚本来判断是否可以解锁,防止被其他线程解锁。 需要注意的是,该工具类只能在单机或者 Redis 集群环境下使用,不支持 Redis Sentinel 模式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值