为防止 缓存穿透的情况,我们有时候会引入 布隆过滤器来 增加一层防护, 具体demo如下
一、 搭建好 Redisson 环境, 详见 https://www.cnblogs.com/cgsdg/p/16225349.html
二、 创建 布隆过滤器, 并添加基础数据
import org.redisson.api.RBloomFilter; import org.redisson.api.RedissonClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component public class BloomDemo { @Autowired private RedissonClient redissonClient; public void createBloom() { RBloomFilter<String> bloomFilter = redissonClient.getBloomFilter("bloom"); bloomFilter.tryInit(1000000, 0.03); //预测插入数量, 误判率 bloomFilter.add("first"); bloomFilter.add("second"); bloomFilter.add("third");; System.out.println(bloomFilter.contains("second")); System.out.println(bloomFilter.contains("automan")); System.out.println(bloomFilter.count()); } }
测试结果为: