1. 引言:当缓存成为防线漏洞
电商平台突遭恶意攻击,每秒数万次查询不存在的商品ID,导致数据库CPU飙升至100%。这种现象就是典型的缓存穿透。本文将手把手教你用布隆过滤器(Bloom Filter)构建缓存系统的"安全门卫",彻底解决这一难题。
2. 布隆过滤器核心原理
布隆过滤器由Burton Howard Bloom于1970年提出,其核心设计包含两个关键要素:
位数组 + 多个哈希函数 = 高效存在性检测
工作流程演示(图示):
- 元素经过k个哈希函数映射到位数组的k个位置
- 所有位置置为1表示元素已存在
- 查询时只要有一个位置为0即可确定不存在

3. Python实现布隆过滤器
3.1 基础版本实现
import mmap
import hashlib
from math import log
class BloomFilter:
def __init__(self, capacity, error_rate=0.001):
self.capacity = capacity
self.error_rate = error_rate
self.bit_size = self._calculate_bit_size()
self.hash_count = self._calculate_hash_count()
self.bit_array = bytearray((self.bit_size + 7) // 8)
def _calculate_bit_size(self):
return int(-self.capacity * log(self.error_rate) / (log(2)**2))
def _calculate_hash_count(self):
return int(log(2) * self.bit_size / self.capacity)
def _hash(self, item):
h = hashlib.md5()
h.update(str(item).</

最低0.47元/天 解锁文章
1194

被折叠的 条评论
为什么被折叠?



