forked from redis/lettuce
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
PingConnectionHandler will periodically send PING commands to Redis Server, and decide whether to reconnect based on whether it fails (the current strategy is to reconnect after three consecutive failures) This is essentially because KeepAlive that only relies on TCP is unreliable, for details, please refer to: redis#2082
1 parent
f48c227
commit 4476bab
Showing
7 changed files
with
350 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
/* | ||
* Copyright 2020-2022 the original author or authors. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* https://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
package io.lettuce.core; | ||
|
||
import java.util.HashMap; | ||
import java.util.Map; | ||
|
||
import io.lettuce.core.protocol.CommandArgs; | ||
import io.lettuce.core.protocol.CommandType; | ||
import io.lettuce.core.protocol.ProtocolKeyword; | ||
|
||
/** | ||
* Includes all blocking commands, some commands must have a blocking parameter. | ||
* | ||
* @author Yang Bodong | ||
*/ | ||
class BlockingCommands { | ||
|
||
private static final Map<ProtocolKeyword, String> BLOCKING_COMMANDS = new HashMap<>(); | ||
|
||
static { | ||
|
||
BLOCKING_COMMANDS.put(CommandType.BLMPOP, ""); | ||
BLOCKING_COMMANDS.put(CommandType.BLMOVE, ""); | ||
BLOCKING_COMMANDS.put(CommandType.BLPOP, ""); | ||
BLOCKING_COMMANDS.put(CommandType.BRPOP, ""); | ||
BLOCKING_COMMANDS.put(CommandType.BRPOPLPUSH, ""); | ||
BLOCKING_COMMANDS.put(CommandType.BZPOPMAX, ""); | ||
BLOCKING_COMMANDS.put(CommandType.BZPOPMIN, ""); | ||
BLOCKING_COMMANDS.put(CommandType.XREAD, "block"); | ||
BLOCKING_COMMANDS.put(CommandType.XREADGROUP, "block"); | ||
} | ||
|
||
/** | ||
* Users can customize and add Module Blocking commands | ||
* @param protocolKeyword the command name | ||
* @param blockingArg the blocking arg. | ||
*/ | ||
public static void addBlockingCommand(ProtocolKeyword protocolKeyword, String blockingArg) { | ||
BLOCKING_COMMANDS.put(protocolKeyword, blockingArg); | ||
} | ||
|
||
/** | ||
* Determine whether a command is a block command, Some commands are block commands only when specific parameters | ||
* are added, for example: xread block xxx. | ||
* @param protocolKeyword the command name | ||
* @param commandArgs the command args | ||
* @return true, blocking; false, not blocking. | ||
*/ | ||
public static boolean isBlockingCommand(ProtocolKeyword protocolKeyword, CommandArgs<?, ?> commandArgs) { | ||
String blockingArg = BLOCKING_COMMANDS.get(protocolKeyword); | ||
if (blockingArg == null) { | ||
return false; | ||
} | ||
if (blockingArg.isEmpty()) { | ||
return true; | ||
} | ||
return commandArgs.containArg(blockingArg); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
156 changes: 156 additions & 0 deletions
156
src/main/java/io/lettuce/core/PingConnectionHandler.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,156 @@ | ||
package io.lettuce.core; | ||
|
||
import java.util.ArrayDeque; | ||
import java.util.concurrent.CancellationException; | ||
import java.util.concurrent.CompletableFuture; | ||
import java.util.concurrent.CompletionException; | ||
import java.util.concurrent.TimeUnit; | ||
import java.util.concurrent.atomic.AtomicInteger; | ||
|
||
import io.lettuce.core.codec.StringCodec; | ||
import io.lettuce.core.protocol.AsyncCommand; | ||
import io.lettuce.core.protocol.Command; | ||
import io.lettuce.core.protocol.CommandHandler; | ||
import io.lettuce.core.protocol.RedisCommand; | ||
import io.lettuce.core.resource.ClientResources; | ||
import io.netty.channel.Channel; | ||
import io.netty.channel.ChannelHandler; | ||
import io.netty.channel.ChannelHandlerContext; | ||
import io.netty.channel.ChannelInboundHandlerAdapter; | ||
import io.netty.util.internal.logging.InternalLogger; | ||
import io.netty.util.internal.logging.InternalLoggerFactory; | ||
|
||
/** | ||
* A netty {@link ChannelHandler} responsible for monitoring (By periodically sending PING commands) Redis alive. | ||
* | ||
* @author Yang Bodong | ||
* @date 2022/11/11 | ||
*/ | ||
@ChannelHandler.Sharable | ||
public class PingConnectionHandler extends ChannelInboundHandlerAdapter { | ||
private static final InternalLogger logger = InternalLoggerFactory.getInstance(PingConnectionHandler.class); | ||
|
||
private final RedisCommandBuilder<String, String> commandBuilder = new RedisCommandBuilder<>(StringCodec.UTF8); | ||
|
||
private static final int MAX_PING_FAILED_TIMES = 3; | ||
|
||
private final AtomicInteger pingFailed = new AtomicInteger(0); | ||
|
||
private final ClientResources clientResources; | ||
|
||
private final ClientOptions clientOptions; | ||
|
||
public PingConnectionHandler(ClientResources clientResources, ClientOptions clientOptions) { | ||
this.clientResources = clientResources; | ||
this.clientOptions = clientOptions; | ||
} | ||
|
||
@Override | ||
public void channelActive(ChannelHandlerContext ctx) throws Exception { | ||
sendPing(ctx); | ||
ctx.fireChannelActive(); | ||
} | ||
|
||
/** | ||
* Periodically send the PING command, if it fails three times in a row, it will initiate a reconnection. | ||
* Ignore exceptions returned by the following PING commands: {@link RedisLoadingException} | ||
* {@link RedisBusyException} | ||
* | ||
* @param ctx the ctx | ||
*/ | ||
private void sendPing(ChannelHandlerContext ctx) { | ||
AsyncCommand<String, String, String> dispatch; | ||
RedisCommand<?, ?, ?> currentCommand = getCurrentCommand(ctx); | ||
if (currentCommand == null || !isBlockingCommand(currentCommand)) { | ||
dispatch = dispatch(ctx.channel(), commandBuilder.ping()); | ||
} else { | ||
dispatch = null; | ||
} | ||
|
||
clientResources.timer().newTimeout(timeout -> { | ||
if (ctx.isRemoved() || !ctx.channel().isActive()) { | ||
return; | ||
} | ||
|
||
RedisCommand<?, ?, ?> cmd = getCurrentCommand(ctx); | ||
if (cmd != null && isBlockingCommand(cmd)) { | ||
sendPing(ctx); | ||
return; | ||
} | ||
|
||
if (dispatch != null && (dispatch.cancel(false) || cause(dispatch) != null)) { | ||
|
||
Throwable cause = cause(dispatch); | ||
|
||
if (!(cause instanceof RedisLoadingException | ||
|| cause instanceof RedisBusyException)) { | ||
if (!dispatch.isCancelled()) { | ||
logger.error("Unable to send PING command over channel: " + ctx.channel(), cause); | ||
} | ||
|
||
if (pingFailed.incrementAndGet() == MAX_PING_FAILED_TIMES) { | ||
logger.error("channel: {} closed due to {} consecutive PING response timeout set in {} ms", | ||
ctx.channel(), MAX_PING_FAILED_TIMES, clientOptions.getPingConnectionInterval()); | ||
pingFailed.set(0); | ||
ctx.channel().close(); | ||
} else { | ||
sendPing(ctx); | ||
} | ||
} else { | ||
pingFailed.set(0); | ||
sendPing(ctx); | ||
} | ||
} else { | ||
pingFailed.set(0); | ||
sendPing(ctx); | ||
} | ||
}, clientOptions.getPingConnectionInterval(), TimeUnit.MILLISECONDS); | ||
} | ||
|
||
private <T> AsyncCommand<String, String, T> dispatch(Channel channel, Command<String, String, T> command) { | ||
|
||
AsyncCommand<String, String, T> future = new AsyncCommand<>(command); | ||
|
||
channel.writeAndFlush(future).addListener(writeFuture -> { | ||
|
||
if (!writeFuture.isSuccess()) { | ||
future.completeExceptionally(writeFuture.cause()); | ||
} | ||
}); | ||
|
||
return future; | ||
} | ||
|
||
protected Throwable cause(CompletableFuture<?> future) { | ||
try { | ||
future.getNow(null); | ||
return null; | ||
} catch (CompletionException ex2) { | ||
return ex2.getCause(); | ||
} catch (CancellationException ex1) { | ||
return ex1; | ||
} | ||
} | ||
|
||
/** | ||
* Determine whether a command is a Blocking command | ||
* @param command the command | ||
* @return true, blocking; false, not blocking. | ||
*/ | ||
private boolean isBlockingCommand(RedisCommand<?, ?, ?> command) { | ||
return BlockingCommands.isBlockingCommand(command.getType(), command.getArgs()); | ||
} | ||
|
||
/** | ||
* Get the command being executed by the current Channel | ||
* @param ctx the ctx | ||
* @return the command. | ||
*/ | ||
private RedisCommand<?, ?, ?> getCurrentCommand(ChannelHandlerContext ctx) { | ||
ArrayDeque<RedisCommand<?, ?, ?>> stack = ctx.channel().attr(CommandHandler.COMMANDS_STACK).get(); | ||
if (stack != null && !stack.isEmpty()) { | ||
return stack.peek(); | ||
} | ||
return null; | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.