背景
- 升級redisson版本后解決了redisson的隊列丟消息問題
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.15.0</version>
</dependency>
- 隨之又出現了其它異常問題,報錯信息有如下幾種:
PingConnectionHandler類報異常,之前分析過這個類,這個異常報得特別多 一晚上將近10w條
image-20210204140409138.png
- RedisExecutor類異常,堆棧如下
at org.redisson.command.RedisExecutor$2.run(RedisExecutor.java:205) ~[redisson-3.15.0.jar!/:3.15.0]
at io.netty.util.HashedWheelTimer$HashedWheelTimeout.expire(HashedWheelTimer.java:672) ~[netty-common-4.1.45.Final.jar!/:4.1.45.Final]
at io.netty.util.HashedWheelTimer$HashedWheelBucket.expireTimeouts(HashedWheelTimer.java:747) ~[netty-common-4.1.45.Final.jar!/:4.1.45.Final]
at io.netty.util.HashedWheelTimer$Worker.run(HashedWheelTimer.java:472) ~[netty-common-4.1.45.Final.jar!/:4.1.45.Final]
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30) ~[netty-common-4.1.45.Final.jar!/:4.1.45.Final]
at java.lang.Thread.run(Thread.java:745) [?:1.8.0_121]
異常信息如下:
image-20210204140659888.png
-
Caused by: org.redisson.client.WriteRedisConnectionException: Channel has been closed!
image-20210204141100695.png
分析結果
上面的報錯信息redisson在最新的版本報錯信息已經明確提示了"Avoid to use blocking commands in Async/JavaRx/Reactive handlers
即不要用阻塞命令,否則會有問題。
經過分析之后,上面幾種異常發生的原因都是因為發送PING命令引發的,原理就是代碼使用了阻塞方法,由netty-threads執行的監聽器或者帶延遲時間的監聽器導致了Redis的請求響應處理錯誤。
解決方案
- 不用redisson的阻塞相關方法,改用非阻塞方式
- 使用redisson的異步非阻塞方式實現代碼,此種方式實現起來,代碼更簡潔,直觀,并且節省了資源。下面是官方給的使用示例
- 禁用redisson ping即可解決使用阻塞方式引發的報錯
官方示例地址:
https://github.com/redisson/redisson/wiki/3.-Operations-execution#31-async-way
image-20210204170547157.png
結合我們自身業務代碼偽代碼如下:
- redisQueueExecutorPool是一個自定義的線程池
public <T extends AbstractRedisQueueJob, R> void doTask(RedisQueueJobListener<T, R> taskEventListener, RBlockingQueue<T> blockingFairQueue) {
//使用非阻塞方式
blockingFairQueue.pollAsync().whenCompleteAsync((res, throwable) -> {
try {
if (Objects.nonNull(res)) {
log.info(res);
RedisQueueJobQueueResult<R> result = taskEventListener.invoke(res);
//判斷是否進行重試 true:結束循環 false:繼續循環
if (taskEventListener.postProcessor(res, result.getResult()) != RedisQueueJobListener.Result.PROCESSING_COMPLETE) {
if (res.getIsDelayQueue()) {
RDelayedQueue<T> delayedQueue = redissonClient.getDelayedQueue(blockingFairQueue);
delayedQueue.offer(res, res.getDelay(), TimeUnit.SECONDS);
} else {
blockingFairQueue.add(res);
}
} else {
log.info("redis隊列任務執行完成,任務對象 {} 結果對象 {}", res, result);
}
}
if (Objects.nonNull(throwable)) {
log.error(throwable.getMessage(), throwable);
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
//在這里休眠一小會兒
//注意這里不是遞歸,不會產生遞歸的方法棧溢出問題,這里是重新調用而已不會堆棧
doTask(taskEventListener, blockingFairQueue);
}
}, redisQueueExecutorPool);
}
關于解決方案我已經提交了issues給官方作者,最近就會有官方回復,讀者可以先關注下我提交給官方的問題:https://github.com/redisson/redisson/issues/3405,https://github.com/redisson/redisson/issues/3412