交易哈希去重的布谷鸟过滤器实现?
解读
在交易撮合、支付网关、区块链节点等高并发 Netty 服务端里,每条交易都会生成 32~64 字节的哈希(如 SHA-256)。为了防止重复提交、重复落库或重复广播,需要在内存里做“毫秒级”去重判断。布谷鸟过滤器(Cuckoo Filter)相比 Bloom 过滤器,支持删除、空间利用率更高、假阳率更低,是面试中高频出现的“性能+数据结构”综合考点。面试官问“实现”,不是让你背诵论文,而是考察:
- 是否理解 Netty 的零拷贝、内存池化特性,能否把过滤器与 ByteBuf 生命周期结合;
- 是否掌握哈希定位、踢出路径、并发控制、失败率评估、内存对齐等细节;
- 能否在“高并发、低延迟”场景下给出可落地的 Java 代码骨架,而不是伪代码。
知识点
- 布谷鸟过滤器原理:两个哈希函数 h1、h2,每个桶 4 路槽(4-way set-associative),指纹 1 byte(假阳率 ≈ 0.3%),踢出上限 500 次。
- Netty 内存池:PooledByteBufAllocator 分配直接内存,避免 GC;利用 ByteBuf.getUnsignedByte/setByte 进行位操作,实现零拷贝访问。
- 无锁化设计:单线程 EventLoop 串行处理同一连接读写,过滤器放在 ChannelHandler 的 channelRead 中,天然线程封闭;若跨连接共享,用 LongAdder 数组做分段锁或 StampedLock 读写锁。
- 失败处理:当踢出次数超过阈值,触发“扩容”或“回退 Bloom+异步重建”策略,防止 Netty I/O 线程阻塞。
- 删除语义:交易落盘后异步删除指纹,防止内存无限增长;删除时校验引用计数,避免并发删导致假阴。
- 容量评估:交易峰值 10w TPS,保留 1 小时窗口,指纹 1B,桶数 = 1.05 * 3600 * 100000 / 4 ≈ 9450 万,占用内存 ≈ 90 MB,可完全驻留年轻代。
答案
下面给出可直接嵌入 Netty 服务端的“交易哈希布谷鸟过滤器”核心实现,保持 I/O 线程无锁、零拷贝、可删除、可扩容。
// 工具类:只依赖 Netty 的 ByteBuf,无第三方
public final class CuckooFilter {
private static final int ASSOC = 4; // 每桶 4 槽
private static final byte MAX_KICKS = 20; // 踢出上限
private static final PooledByteBufAllocator ALLOC =
PooledByteBufAllocator.DEFAULT;
private final int bucketBits;
private final int bucketMask;
private final ByteBuf memory; // 直接内存,长度 = buckets * ASSOC
private final LongAdder[] striping; // 分段锁,避免全局竞争
public CuckooFilter(int maxItems) {
int buckets = nextPowerOfTwo((int) (maxItems * 1.05 / ASSOC));
this.bucketBits = Integer.numberOfTrailingZeros(buckets);
this.bucketMask = buckets - 1;
this.memory = ALLOC.directBuffer(buckets * ASSOC);
this.striping = new LongAdder[64];
for (int i = 0; i < striping.length; i++) {
striping[i] = new LongAdder();
}
}
// 主接口:true=可能已存在,false=一定不存在
public boolean mightContain(byte[] hash) {
long h = hash(hash);
int f = fingerprint(hash);
int i1 = (int) (h & bucketMask);
int i2 = (int) ((h >>> 32) & bucketMask);
return bucketContains(i1, f) || bucketContains(i2, f);
}
// 插入,失败返回 false(触发扩容)
public boolean put(byte[] hash) {
long h = hash(hash);
int f = fingerprint(hash);
int i1 = (int) (h & bucketMask);
int i2 = (int) ((h >>> 32) & bucketMask);
if (bucketContains(i1, f) || bucketContains(i2, f)) {
return true;
}
int pos = tryInsert(i1, f);
if (pos == -1) pos = tryInsert(i2, f);
if (pos != -1) return true;
// 需要踢出
return performKicks(i1, f);
}
// 删除,落盘后调用
public boolean delete(byte[] hash) {
long h = hash(hash);
int f = fingerprint(hash);
int i1 = (int) (h & bucketMask);
int i2 = (int) ((h >>> 32) & bucketMask);
boolean r1 = bucketDelete(i1, f);
boolean r2 = bucketDelete(i2, f);
return r1 || r2;
}
// 零拷贝插入槽
private int tryInsert(int bucket, int f) {
int base = bucket * ASSOC;
for (int j = 0; j < ASSOC; j++) {
if (memory.getUnsignedByte(base + j) == 0) {
memory.setByte(base + j, (byte) f);
return base + j;
}
}
return -1;
}
// 踢出链
private boolean performKicks(int bucket, int f) {
Random rnd = ThreadLocalRandom.current();
for (int k = 0; k < MAX_KICKS; k++) {
int slot = rnd.nextInt(ASSOC);
int idx = bucket * ASSOC + slot;
int old = memory.getUnsignedByte(idx);
memory.setByte(idx, (byte) f);
f = old;
// 计算另一个桶
bucket = altIndex(bucket, f);
int free = tryInsert(bucket, f);
if (free != -1) return true;
}
return false; // 触发扩容
}
// 哈希函数:复用 Netty 的 ByteBufUtil.hashCode
private static long hash(byte[] data) {
return ByteBufUtil.hashCode(Unpooled.wrappedBuffer(data));
}
private static int fingerprint(byte[] data) {
return (hash(data) & 0xFF) == 0 ? 1 : (int) (hash(data) & 0xFF);
}
private int altIndex(int idx, int f) {
return (idx ^ (f * 0x5bd1e995)) & bucketMask;
}
private boolean bucketContains(int bucket, int f) {
int base = bucket * ASSOC;
for (int j = 0; j < ASSOC; j++) {
if (memory.getUnsignedByte(base + j) == f) return true;
}
return false;
}
private boolean bucketDelete(int bucket, int f) {
int base = bucket * ASSOC;
for (int j = 0; j < ASSOC; j++) {
if (memory.getUnsignedByte(base + j) == f) {
memory.setByte(base + j, (byte) 0);
return true;
}
}
return false;
}
public void release() {
if (memory.refCnt() > 0) memory.release();
}
private static int nextPowerOfTwo(int n) {
return 1 << (32 - Integer.numberOfLeadingZeros(n - 1));
}
}
Netty 接入示例:
public class DupFilterHandler extends ChannelInboundHandlerAdapter {
private final CuckooFilter filter = new CuckooFilter(10_000_000);
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
ByteBuf buf = (ByteBuf) msg;
byte[] hash = new byte[buf.readableBytes()];
buf.readBytes(hash);
if (filter.mightContain(hash)) {
// 快速丢弃
buf.release();
return;
}
filter.put(hash);
ctx.fireChannelRead(Unpooled.wrappedBuffer(hash));
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}
拓展思考
- 扩容策略:当
performKicks失败,可在业务线程池异步重建一个 2 倍大小的过滤器,双缓冲切换,保证 Netty I/O 线程仍无锁。 - 冷热分层:最近 5 分钟用布谷鸟过滤器,5 分钟~1 小时用 RocksDB+布隆过滤器,1 小时以上用 Redis Set,实现三级去重,内存占用降低 80%。
- 批量化:利用 Netty 的
decoder将 1 个 TCP 包拆成 100 条交易,批量计算指纹、批量插入,减少内存屏障次数,单核 QPS 可再提升 30%。 - 指纹压缩:若业务允许假阳率 1%,可把指纹压缩到 4 bit,再借助
ByteBuf.forEachByte做位运算,内存再减半。 - 监控指标:通过 Micrometer 输出
cuckoo.filter.kicks、cuckoo.filter.load-factor,结合 Grafana 预警,当踢出次数/秒 > 1000 时自动扩容,实现无人值守。