Redis的缓存穿透的解决方案-布隆过滤器BloomFilter

直接上代码

import java.util.Arrays;
import java.util.BitSet;

/**
 * @Description
 * @Author tearriy
 * @Date 2022/04/08 10:21
 */
public class MyBloomFilter {
    //后面hash函数会用到,用来生成不同的hash值,可以随便给,但别给奇数
    private final int[] ints = {6, 8, 16, 38, 58, 68};
    private Integer currentBeanCount = 0;
    //你的布隆过滤器容量
    private int DEFAULT_SIZE = Integer.MAX_VALUE;
    //bit数组,用来存放结果
    private final BitSet bitSet = new BitSet(DEFAULT_SIZE);

    public MyBloomFilter() {
    }

//    public MyBloomFilter(int size) {
//        if (size <= (2 << 8)) throw new RuntimeException("size is too small");
//        DEFAULT_SIZE = size;
//    }

//    //获取当前过滤器的对象数量
//    public Integer getCurrentBeanCount() {
//        return currentBeanCount;
//    }

    //计算出key的hash值,并将对应下标置为true
    public void push(Object key) {
        Arrays.stream(ints).forEach(i -> {
            bitSet.set(hash(key, i));
//            System.out.println(bitSet);
        });
        currentBeanCount++;

    }

    //判断key是否存在,true不一定说明key存在,但是false一定说明不存在
    public boolean contain(Object key) {
        boolean result = true;
        for (int i : ints) {
            result = result && bitSet.get(hash(key, i));
        }
        return result;
    }

    //hash算法,借鉴了hashmap的算法
    private int hash(Object key, int i) {
        int h;
        int index = key == null ? 0 : (DEFAULT_SIZE - 1 - i) & ((h = key.hashCode()) ^ (h >>> 16));
        return index > 0 ? index : -index;
    }

    public static void main(String[] args) {
        MyBloomFilter bf = new MyBloomFilter ();

        long start  = System.currentTimeMillis();
        bf.push("张学友");
        bf.push("郭德纲");
        bf.push("蔡徐鸡");
        bf.push(666);
        for (int i = 0; i < 100000000; i++) {
            bf.push("郭德纲"+i);
        }
        long end  = System.currentTimeMillis();
        System.out.println("创建用时:"+(end-start));

        System.out.println(bf.contain("张学友"));//true
        System.out.println(bf.contain("张学友 "));//false
        System.out.println(bf.contain("张学友1"));//false
        System.out.println(bf.contain("郭德纲"));//true
        System.out.println(bf.contain("蔡徐老"));//false
        System.out.println(bf.contain(666));//true
        System.out.println(bf.contain(888));//false

        System.out.println(bf.contain("郭德纲98985474"));  //true
        long end2 = System.currentTimeMillis();
        System.out.println("查询用时:"+(end2-end));
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

StevenTang~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值