一、背景
在Redis业务运维中,经常遇到一类稳定性问题:
业务代码不当使用HGETALL、LRANGE 0 -1、SMEMBERS、KEYS *等全量查询命令,单个返回RESP响应Bulk字符串达到数MB甚至几十MB。
带来的风险:
- Redis服务端网卡打满,带宽抢占;
- 长连接上Pipeline队列堆积,后续命令RTT飙升;
- 客户端内存突增、GC抖动;
- 代理层缓冲区打爆,引发OOM。
直接在Redis服务端没有原生配置限制单次响应大小;客户端改造推动周期长。 最优收口方案:在Redis代理网关层做统一检测。
方案选型说明
两种动作模式:
- WARN_ONLY(推荐生产):打印结构化告警日志,继续透传响应,不中断业务;
- REJECT(测试环境):返回错误并关闭连接,禁止大包返回(风险高,Pipeline场景会协议错位)。
二、核心原理:RESP协议检测要点
Redis通信采用RESP协议,代理必须理解协议结构,不能简单按TCP缓冲区字节数判断包大小。
RESP响应类型:
| 标记 | 类型 | 说明 | 是否容易产生大包 |
|---|---|---|---|
+ | 简单字符串 | +OK\r\n | 否 |
- | 错误 | -ERR xxx\r\n | 否 |
: | 整数 | :123\r\n | 否 |
$ | Bulk String | $<len>\r\n数据\r\n,$-1代表nil | ✅ 重点检测 |
* | Array | *<count>\r\n后跟N个RESP元素,递归结构 | ✅ 需要递归遍历子元素 |
⚠️ 重点坑:
HGETALL返回的是*数组,数组内部每一个元素都是$Bulk字符串;外层数组只标记元素个数,数组本身没有总长度字段,必须递归遍历内部所有Bulk。
示例:
HGETALL bighash返回*10000\r\n$5\r\nname\r\n$100000\r\n...,单个Bulk超过阈值就告警。
另外要控制递归深度,防止恶意嵌套RESP报文造成代理栈溢出,增加最大递归深度保护(默认128)。
三、整体架构
双向通道:
- 上行(Client → Redis):解析命令,记录当前命令、Key,用于告警日志输出;
- 下行(Redis → Client):解析RESP响应,递归检测Bulk长度,命中阈值输出告警;
- 代理使用双端Channel:客户端Channel <-> Redis后端Channel,转发ByteBuf。
关键:命令和响应是顺序匹配(Redis Pipeline),需要维护pendingCommand队列,响应回来时绑定当时的cmd、key、clientIp。
四、完整代码实现
4.1 Maven依赖
<dependencies>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.112.Final</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.12</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.4.11</version>
</dependency>
</dependencies>
4.2 配置常量类
public class RedisProxyConfig {
/** 大包阈值 1MB */
public static final long MAX_BULK_SIZE = 1024L * 1024L;
/** 最大递归深度,防止恶意嵌套 */
public static final int MAX_RECURSION_DEPTH = 128;
public enum ActionMode {
WARN_ONLY, REJECT
}
/** 生产环境默认 WARN_ONLY */
public static final ActionMode ACTION_MODE = ActionMode.WARN_ONLY;
}
4.3 RESP模型与Pending上下文
用来保存等待响应的命令信息,告警时打印cmd、key、客户端IP
public class PendingCmd {
private final String cmd;
private final String key;
private final String clientIp;
public PendingCmd(String cmd, String key, String clientIp) {
this.cmd = cmd;
this.key = key;
this.clientIp = clientIp;
}
public String getCmd() { return cmd; }
public String getKey() { return key; }
public String getClientIp() { return clientIp; }
}
4.4 核心:RespBulkCheckHandler(响应链路检测)
这是整个方案的核心,放在后端返回方向的InboundHandler,递归解析RESP。 注意:Netty是ByteBuf流式,读取时要维护readerIndex,不修改原始转发流(只读检测,不消费报文)。
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.Queue;
public class RespBulkCheckHandler extends ChannelInboundHandlerAdapter {
private static final Logger log = LoggerFactory.getLogger(RespBulkCheckHandler.class);
/** 待匹配的命令队列,Pipeline场景按顺序匹配响应 */
private final Queue<PendingCmd> pendingQueue = new LinkedList<>();
public void enqueuePending(PendingCmd cmd) {
pendingQueue.offer(cmd);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof ByteBuf buf)) {
super.channelRead(ctx, msg);
return;
}
// 复制一份用于检测,原始buf继续透传给客户端
ByteBuf dup = buf.duplicate();
dup.markReaderIndex();
PendingCmd pending = pendingQueue.peek();
try {
parseResp(dup, 0, pending);
} catch (NeedMoreDataException e) {
// 数据不够,等下一次read,不告警
} catch (RespOverLimitException e) {
if (pending != null) {
log.warn("[REDIS_PROXY_BIG_RESP_ALERT] clientIp={}, cmd={}, key={}, bulkLen={}, threshold={}",
pending.getClientIp(), pending.getCmd(), pending.getKey(), e.getLen(), RedisProxyConfig.MAX_BULK_SIZE);
// 埋点指标:可以在这里增加Prometheus指标计数
// metricRegistry.counter("redis_proxy_resp_over_limit").inc();
}
if (RedisProxyConfig.ACTION_MODE == RedisProxyConfig.ActionMode.REJECT) {
// 拦截模式:返回错误报文,关闭连接(必须关,防止协议错位)
ByteBuf err = ctx.alloc().buffer();
err.writeBytes("-ERR Response payload exceeds proxy limit 1MB\r\n".getBytes(StandardCharsets.UTF_8));
ctx.writeAndFlush(err);
ctx.close();
ReferenceCountUtil.release(buf);
return;
}
} finally {
dup.resetReaderIndex();
dup.release();
}
// RESP响应解析完成,弹出一条pending命令
if (dup.readableBytes() == 0) {
pendingQueue.poll();
}
super.channelRead(ctx, msg);
}
/**
* 递归解析RESP
* @param buf 待解析buffer
* @param depth 当前递归深度
* @param pending 关联命令上下文
*/
private void parseResp(ByteBuf buf, int depth, PendingCmd pending) throws NeedMoreDataException, RespOverLimitException {
if (depth > RedisProxyConfig.MAX_RECURSION_DEPTH) {
throw new RespOverLimitException(0, "resp nested too deep");
}
if (!buf.isReadable()) {
throw new NeedMoreDataException();
}
byte type = buf.readByte();
switch (type) {
case '+', '-', ':' -> {
// 简单类型,读到\r\n
readCrLf(buf);
}
case '$' -> {
long len = readLongLine(buf);
if (len == -1) {
// nil $-1\r\n
return;
}
if (len > RedisProxyConfig.MAX_BULK_SIZE) {
throw new RespOverLimitException(len, "bulk over size");
}
// 跳过payload + \r\n
skipN(buf, len + 2);
}
case '*' -> {
long count = readLongLine(buf);
for (long i = 0; i < count; i++) {
parseResp(buf, depth + 1, pending);
}
}
default -> throw new RespOverLimitException(0, "unknown resp type:" + (char) type);
}
}
/** 读取一行直到\r\n,返回数值 */
private long readLongLine(ByteBuf buf) throws NeedMoreDataException {
StringBuilder sb = new StringBuilder();
while (true) {
if (!buf.isReadable()) throw new NeedMoreDataException();
byte b = buf.readByte();
if (b == '\r') {
if (!buf.isReadable() || buf.readByte() != '\n') {
throw new NeedMoreDataException();
}
return Long.parseLong(sb.toString());
}
sb.append((char) b);
}
}
/** 读到\r\n,丢弃内容 */
private void readCrLf(ByteBuf buf) throws NeedMoreDataException {
while (true) {
if (!buf.isReadable()) throw new NeedMoreDataException();
byte b = buf.readByte();
if (b == '\r') {
if (!buf.isReadable() || buf.readByte() != '\n') {
throw new NeedMoreDataException();
}
return;
}
}
}
private void skipN(ByteBuf buf, long n) throws NeedMoreDataException {
if (buf.readableBytes() < n) {
throw new NeedMoreDataException();
}
buf.skipBytes((int) n);
}
public static class NeedMoreDataException extends Exception {}
public static class RespOverLimitException extends Exception {
private final long len;
public RespOverLimitException(long len, String msg) {
super(msg);
this.len = len;
}
public long getLen() { return len; }
}
}
4.5 客户端命令解析Handler(上行链路)
负责解析客户端发来的Redis命令,提取cmd、key,入队pendingQueue,用于告警时打印上下文
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import java.nio.charset.StandardCharsets;
public class RedisCmdParseHandler extends ChannelInboundHandlerAdapter {
private final RespBulkCheckHandler checkHandler;
public RedisCmdParseHandler(RespBulkCheckHandler checkHandler) {
this.checkHandler = checkHandler;
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!(msg instanceof ByteBuf buf)) {
super.channelRead(ctx, msg);
return;
}
ByteBuf dup = buf.duplicate();
dup.markReaderIndex();
try {
// 简化实现:只解析数组格式命令 *N\r\n$len\r\nCMD\r\n$len\r\nKEY...
if (dup.readByte() == '*') {
long argCnt = readLongLine(dup);
String cmd = readBulk(dup);
String key = null;
if (argCnt >= 2) {
key = readBulk(dup);
}
String clientIp = ((SocketChannel) ctx.channel()).remoteAddress().getAddress().getHostAddress();
checkHandler.enqueuePending(new PendingCmd(cmd, key, clientIp));
}
} catch (RespBulkCheckHandler.NeedMoreDataException ignored) {
// 半包,等后续包
} finally {
dup.resetReaderIndex();
dup.release();
}
super.channelRead(ctx, msg);
}
private long readLongLine(ByteBuf buf) throws RespBulkCheckHandler.NeedMoreDataException {
StringBuilder sb = new StringBuilder();
while (true) {
if (!buf.isReadable()) throw new RespBulkCheckHandler.NeedMoreDataException();
byte b = buf.readByte();
if (b == '\r') {
if (!buf.isReadable() || buf.readByte() != '\n') {
throw new RespBulkCheckHandler.NeedMoreDataException();
}
return Long.parseLong(sb.toString());
}
sb.append((char) b);
}
}
private String readBulk(ByteBuf buf) throws RespBulkCheckHandler.NeedMoreDataException {
if (buf.readByte() != '$') {
return null;
}
long len = readLongLine(buf);
if (len == -1) return null;
byte[] data = new byte[(int) len];
buf.readBytes(data);
buf.skipBytes(2); // \r\n
return new String(data, StandardCharsets.UTF_8);
}
}
4.6 Proxy启动入口(简易骨架)
生产上后端连接池、断线重连、Redis集群路由、认证、超时、限流都需要额外完善,这里只保留核心链路演示
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
public class RedisProxyServer {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup boss = new NioEventLoopGroup(1);
NioEventLoopGroup worker = new NioEventLoopGroup();
try {
ServerBootstrap b = new ServerBootstrap();
b.group(boss, worker)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) {
RespBulkCheckHandler checkHandler = new RespBulkCheckHandler();
ChannelPipeline p = ch.pipeline();
// 上行:客户端命令解析
p.addLast(new RedisCmdParseHandler(checkHandler));
// 双向转发Handler(这里省略后端转发逻辑)
p.addLast(new RedisBackendForwardHandler(checkHandler));
}
})
.option(ChannelOption.SO_BACKLOG, 1024)
.childOption(ChannelOption.SO_KEEPALIVE, true);
ChannelFuture f = b.bind(63790).sync();
f.channel().closeFuture().sync();
} finally {
boss.shutdownGracefully();
worker.shutdownGracefully();
}
}
}
RedisBackendForwardHandler 是双向转发桥接器,职责:
- 客户端Channel收到(<len>\r\n数据\r\n,)转发给后端Redis Channel;
- 后端Redis Channel收到响应,流入RespBulkCheckHandler检测,再转发客户端; 标准双端转发代码网上成熟,本文重心放在大包检测逻辑。
五、日志输出样例
WARN [REDIS_PROXY_BIG_RESP_ALERT] clientIp=10.10.10.123, cmd=HGETALL, key=order:hash:10086, bulkLen=1258000, threshold=1048576
结构化日志,直接接入ELK、Loki检索,配置告警规则。
配套埋点:增加Prometheus指标 redis_proxy_resp_over_limit_total{cmd="HGETALL"},按命令维度统计。
六、生产落地注意事项(重点)
6.1 WARN_ONLY vs REJECT
- WARN_ONLY(推荐):不破坏业务,先观测哪些Key、哪些命令持续出大包,推动业务分页改造(
HSCAN、SSCAN、LIMIT分页); - REJECT:仅测试环境使用。一旦拦截大包,必须关闭连接;Redis Pipeline下如果丢弃响应,后续命令和响应顺序错乱,客户端会收到脏数据。
6.2 内存模型优势
代码中使用ByteBuf.duplicate()做只读检测,不会把完整大包拷贝到堆内存,属于流式检测,内存开销恒定,不会因为几十MB大包导致代理OOM。
6.3 边界场景覆盖
✅ 单个Bulk字符串大包 GET bigkey
✅ Array内部嵌套Bulk大包 HGETALL / LRANGE / SMEMBERS
✅ Redis Pipeline批量命令
✅ 嵌套深度保护,防止DoS
✅ nil Bulk($-1\r\n)跳过检测
6.4 待补充增强点(生产版本)
- 增加白名单:某些历史大Key允许超过阈值,配置key白名单不告警;
- 阈值动态配置:Apollo/Nacos热更新
MAX_BULK_SIZE,不需要重启代理; - 区分命令黑白名单:默认禁止
KEYS全量扫描; - 增加响应总大小统计(数组所有Bulk累加),支持“整个响应总和超限告警”;
- Redis Cluster路由、Slot转发、后端连接池、心跳保活、密码认证;
- 限流、慢命令监控、连接审计。
注意:本文归作者所有,未经作者允许,不得转载