项目场景
springboot 2.x 集成了 Letture。项目启动后,开启一个线程在后台不停地 blpop redis的队列list 。一段时间后,出现连接超时的问题。springboot版本是2.2.5.RELEASE, Letture的版本是6.1.4.RELEASE。
为什么用blpop命令呢? 因为BLPOP 是列表的阻塞式(blocking)弹出原语。 它是 LPOP 命令的阻塞版本,当给定列表内没有任何元素可供弹出的时候,连接将被BLPOP 命令阻塞,直到等待超时或发现可弹出元素为止。 当给定多个 key 参数时,按参数 key的先后顺序依次检查各个列表,弹出第一个非空列表的头元素。
问题描述
项目启动一段时间后,(大概1分钟)吧。emmemem,抛出以下异常
io.lettuce.core.RedisCommandTimeoutException: Command timed out after 1 minute(s)
at io.lettuce.core.internal.ExceptionFactory.createTimeoutException(ExceptionFactory.java:53)
at io.lettuce.core.internal.Futures.awaitOrCancel(Futures.java:246)
at io.lettuce.core.FutureSyncInvocationHandler.handleInvocation(FutureSyncInvocationHandler.java:75)
at io.lettuce.core.internal.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:80)
at com.sun.proxy.$Proxy191.blpop(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at io.lettuce.core.support.ConnectionWrapping$DelegateCloseToConnectionInvocationHandler.handleInvocation(ConnectionWrapping.java:215)
at io.lettuce.core.internal.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:80)
at com.sun.proxy.$Proxy191.blpop(Unknown Source)
at com.fish.pro.framework.core.utils.RedisUtil.blpop(RedisUtil.java:787)
at com.fish.pro.infrastructure.queue.redis.RedisQueue.run(RedisQueue.java:41)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:748)
源代码片段
public static void init(String host, int port, int database, String password, int minIdle, int maxIdle, int maxTotal) throws Exception {
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMinIdle(minIdle);
genericObjectPoolConfig.setMaxTotal(maxTotal);
RedisURI uri =
RedisURI.builder().withHost(host).withPort(port).withDatabase(database)
.withPassword(password.toCharArray()).build();
RedisClient client = RedisClient.create(uri);
GenericObjectPool<StatefulRedisConnection<String, String>> pool =
ConnectionPoolSupport.createGenericObjectPool(() -> client.connect(),genericObjectPoolConfig);
pool.preparePool();
RedisUtil.init(pool);
}
public static <T> T blpop(String key,Class<T> clazz) {
StatefulRedisConnection<String, String> connection = null;
try {
connection = pool.borrowObject();
RedisCommands<String, String> commands = connection.sync();
KeyValue<String, String> keyValue = commands.blpop(0, key);
T obj = JSONUtil.parseObject(keyValue.getValue(), clazz);
return obj;
} catch (Exception e) {
log.error("RedisUtil get exceptions", e);
} finally {
close(connection);
}
return null;
}
原因分析
查阅官网给出的解释:
The configured command timeout applies without considering command-specific timeouts.
翻译过来的意思:配置的命令超时不考虑特定命令的超时。
解决方案
官网 给出的解决方案:
There are various options:
-
Configure a higher default timeout.
-
Consider a timeout that meets the default timeout when calling blocking commands.
-
Configure
TimeoutOptions
with a customTimeoutSource
TimeoutOptions timeoutOptions = TimeoutOptions.builder().timeoutSource(new TimeoutSource() { @Override public long getTimeout(RedisCommand<?, ?, ?> command) { if (command.getType() == CommandType.BLPOP) { return TimeUnit.MILLISECONDS.toNanos(CommandArgsAccessor.getFirstInteger(command.getArgs())); } // -1 indicates fallback to the default timeout return -1; } }).build();
结合官网给出的解决方案, 最终把代码修改为
public static void init(String host, int port, int database, String password, int minIdle, int maxIdle, int maxTotal) throws Exception {
TimeoutOptions timeoutOptions = TimeoutOptions.builder().timeoutSource(new TimeoutOptions.TimeoutSource() {
@Override
public long getTimeout(RedisCommand<?, ?, ?> command) {
if (command.getType() == CommandType.BLPOP) {
return TimeUnit.MILLISECONDS.toNanos(CommandArgsAccessor.getFirstInteger(command.getArgs()));
}
// -1 indicates fallback to the default timeout
return -1;
}
}).build();
ClientOptions clientOptions = ClientOptions.builder().timeoutOptions(timeoutOptions).build();
GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
genericObjectPoolConfig.setMaxIdle(maxIdle);
genericObjectPoolConfig.setMinIdle(minIdle);
genericObjectPoolConfig.setMaxTotal(maxTotal);
RedisURI uri = RedisURI.builder().withHost(host).withPort(port).withDatabase(database).withPassword(password.toCharArray()).build();
RedisClient client = RedisClient.create(uri);
//解决阻塞BLPOP超时的问题或直接设置 client.setDefaultTimeout(Duration.ZERO)
client.setOptions(clientOptions);
GenericObjectPool<StatefulRedisConnection<String, String>> pool = ConnectionPoolSupport.createGenericObjectPool(() -> client.connect(), genericObjectPoolConfig);
pool.preparePool();
RedisUtil.init(pool);
}
修改后,暂没有发现 连接超时现象出现。如有问题,请指导修正~