欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

URL去重:布隆过滤器的简单实现

程序员文章站 2022-05-03 15:51:35
...
/**
* 如何不采集重复的网页?去重可以使用布隆过滤器,每个线程使用一个bitarray,
* 里面保存本批源页面上次抓取的页面的哈希值情况,抓取下来的源页面分析链接后,
* 去这个bitarray里判断以前有没有抓过这个页面,没有的话就抓下来,抓过的话就不管了。
* 假设一个源页面有30个链接,一批10W个源页面,300w个链接的bitarray应该也不会占太大内存。
* 所以有个五六个线程同时处理也是没问题的。
* **/

public class SimpleBloomFilter {
private static final int DEFAULT_SIZE = 2 << 24;
private static final int[] seeds = new int[] { 7, 11, 13, 31, 37, 61, };
private BitSet bits = new BitSet(DEFAULT_SIZE);
private SimpleHash[] func = new SimpleHash[seeds.length];

public SimpleBloomFilter() {
for (int i = 0; i < seeds.length; i++) {
func[i] = new SimpleHash(DEFAULT_SIZE, seeds[i]);
}
}

public static void main(String[] args) {
String value = "[email protected]";
SimpleBloomFilter filter = new SimpleBloomFilter();
System.out.println(filter.contains(value));
filter.add(value);
System.out.println(filter.contains(value));
}


// 覆盖方法,把URL添加进来
public void add(CrawlUrl value) {
if (value != null)
add(value.getOriUrl());
}

// 覆盖方法,把URL添加进来
public void add(String value) {
for (SimpleHash f : func)
bits.set(f.hash(value), true);
}

// 覆盖方法,是否包含URL
public boolean contains(CrawlUrl value) {
return contains(value.getOriUrl());
}

// 覆盖方法,是否包含URL
public boolean contains(String value) {
if (value == null) {
return false;
}
boolean ret = true;
for (SimpleHash f : func) {
ret = ret && bits.get(f.hash(value));
}
return ret;
}

public static class SimpleHash {
private int cap;
private int seed;

public SimpleHash(int cap, int seed) {
this.cap = cap;
this.seed = seed;
}
public int hash(String value) {
int result = 0;
int len = value.length();
for (int i = 0; i < len; i++) {
result = seed * result + value.charAt(i);
}
return (cap - 1) & result;
}
}
}
相关标签: 应用服务器