发布于2026-07-06 阅读(0)
扫一扫,手机访问
今天我们来聊聊Ja va中的HyperLogLog算法——一个用极小内存就能搞定超大规模去重统计的利器。简单说,它的核心价值在于:只需要KB级别的内存,就能对TB级数据的独立元素数量(也就是基数)给出一个相当靠谱的估算结果,误差通常控制在2%左右。听起来有点不可思议?我们一步步拆解。
HyperLogLog是一个概率性基数估计算法。它不是老老实实存下每一个独立元素,而是通过记录哈希值前面最长连续零的位数,来反推整体的去重数量。
// 简化理解:不是存储所有元素,而是记录"最长连续零的位数"
// 例如:hash("apple") = 00101000... (前导零3个)
// hash("banana") = 00011001... (前导零4个)
// 通过最大前导零位数 m,估算基数 ≈ 2^m
说到具体落地,Ja va世界里主要有三种玩法:直接用Google Gua va、用Redis的HyperLogLog命令,或者自己手撸一个简化版用于教学。先说最常用的方案——Google Gua va,它封装得非常优雅。
import com.google.common.hash.Hashing;
import com.google.common.math.LongMath;
import ja va.util.concurrent.ThreadLocalRandom;
public class HyperLogLogExample {
public static void main(String[] args) {
// 创建HLL,log2m=14 → 16384个桶,内存约12KB
com.google.common.hash.HyperLogLog hll =
com.google.common.hash.HyperLogLog.builder()
.withPrecision(14) // 精度控制,14是平衡值
.build();
// 添加100万条数据
for (int i = 0; i < 1_000_000; i++) {
String element = "user_" + ThreadLocalRandom.current().nextInt(2_000_000);
hll.add(element.getBytes());
}
// 估算基数
long estimate = hll.cardinality(); // 约100万
System.out.println("估算基数: " + estimate);
}
}
生产环境里,Redis的HyperLogLog是更高频的选择,它把精力全集中在核心功能,你用起来也很方便。
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Pipeline;
public class RedisHLLDemo {
private Jedis jedis = new Jedis("localhost", 6379);
// 添加元素
public void addVisitors(String date, String... userIds) {
Pipeline pipeline = jedis.pipelined();
for (String userId : userIds) {
pipeline.pfadd("hll:visitors:" + date, userId);
}
pipeline.sync();
}
// 获取日活估算
public long getDailyActiveUsers(String date) {
return jedis.pfcount("hll:visitors:" + date);
}
// 合并多天数据(去重统计周活)
public long getWeeklyActiveUsers(String weekKey, String... dates) {
String[] keys = new String[dates.length];
for (int i = 0; i < dates.length; i++) {
keys[i] = "hll:visitors:" + dates[i];
}
return jedis.pfcount(keys); // Redis自动合并去重
}
}
如果你只想理解其内部实现机制,一个简化版的手动实现是很好的教学工具。
import ja va.security.MessageDigest;
import ja va.security.NoSuchAlgorithmException;
import ja va.util.Arrays;
public class SimpleHyperLogLog {
private final int m; // 桶数量
private final int p; // 精度(log2 m)
private final byte[] registers;
private final double alpha; // 修正系数
public SimpleHyperLogLog(int p) {
this.p = p;
this.m = 1 << p; // 2^p
this.registers = new byte[m];
this.alpha = calculateAlpha(m);
}
public void add(String element) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hash = md.digest(element.getBytes());
// 前p位决定桶索引
int bucket = 0;
for (int i = 0; i < p; i++) {
bucket = (bucket << 1) | ((hash[i >> 3] >> (7 - (i & 7))) & 1);
}
// 剩余位数中计算前导零个数
int leadingZeros = countLeadingZeros(hash, p);
// 更新桶中最大值
if (leadingZeros > registers[bucket]) {
registers[bucket] = (byte) leadingZeros;
}
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public long cardinality() {
// 调和平均
double sum = 0.0;
for (byte reg : registers) {
sum += 1.0 / (1 << reg);
}
double estimate = alpha * m * m / sum;
// 小范围修正
if (estimate <= 2.5 * m) {
int zeroCount = 0;
for (byte reg : registers) {
if (reg == 0) zeroCount++;
}
if (zeroCount > 0) {
estimate = m * Math.log((double) m / zeroCount);
}
}
return Math.round(estimate);
}
private int countLeadingZeros(byte[] hash, int startBit) {
int count = 0;
for (int i = startBit; i < hash.length * 8 && count < 64; i++) {
int byteIdx = i >> 3;
int bitIdx = 7 - (i & 7);
if (((hash[byteIdx] >> bitIdx) & 1) == 1) {
break;
}
count++;
}
return count;
}
private double calculateAlpha(int m) {
// 不同m值的修正系数
switch (m) {
case 16: return 0.673;
case 32: return 0.697;
case 64: return 0.709;
default: return 0.7213 / (1 + 1.079 / m);
}
}
}
说到应用,HyperLogLog最经典的场景就是网站UV统计。日活、周活、月活这些指标,用HLL来做简直是天作之合。
@Service
public class AnalyticsService {
@Autowired
private StringRedisTemplate redisTemplate;
// 记录用户访问
public void recordVisit(Long userId, LocalDate date) {
String key = "hll:uv:" + date.toString();
redisTemplate.opsForHyperLogLog().add(key, userId.toString());
}
// 获取日活
public Long getDailyUV(LocalDate date) {
String key = "hll:uv:" + date.toString();
return redisTemplate.opsForHyperLogLog().size(key);
}
// 获取周活(合并7天)
public Long getWeeklyUV(LocalDate endDate) {
String[] keys = new String[7];
for (int i = 6; i >= 0; i--) {
keys[6 - i] = "hll:uv:" + endDate.minusDays(i).toString();
}
return redisTemplate.opsForHyperLogLog().union(keys);
}
}
在处理数百万级别的日志时,比如要统计独立IP数量,用HyperLogLog就能在内存和速度之间找到一个绝佳的平衡点。
// 统计百万级日志中的独立IP
public class LogAnalyzer {
private HyperLogLog hll = HyperLogLog.builder()
.withPrecision(14) // 适合百万级数据
.build();
public void processLogFile(String filePath) {
try (Stream lines = Files.lines(Paths.get(filePath))) {
lines.map(line -> extractIP(line))
.forEach(ip -> hll.add(ip.getBytes()));
}
}
public long getUniqueIPCount() {
return hll.cardinality();
}
}
推荐系统里需要避免重复推荐,如果一个用户已经看过某个内容,下次就不该再推。用HLL为每个用户维护一个小结构,就能高效判断并记录。
@Component
public class RecommendationDeduplicator {
// 每个用户维护一个HLL,记录已推荐内容
private final Map userHLLCache = new ConcurrentHashMap<>();
public boolean isRecommended(Long userId, String contentId) {
HyperLogLog hll = userHLLCache.computeIfAbsent(userId,
k -> HyperLogLog.builder().withPrecision(12).build());
boolean exists = hll.cardinality() > 0 &&
hll.contains(contentId.getBytes()); // Gua va支持contains
if (!exists) {
hll.add(contentId.getBytes());
}
return exists;
}
}
数据库优化里,估算WHERE条件的选择性是个经典需求。HyperLogLog可以帮我们快速估算某一列的去重值数量,从而优化执行计划。
// 估算SQL WHERE条件的选择性,优化执行计划
public class QueryEstimator {
private final Map columnDistinctHLL = new ConcurrentHashMap<>();
public void buildStatistics(ResultSet rs) throws SQLException {
while (rs.next()) {
for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++) {
String value = rs.getString(i);
String colName = rs.getMetaData().getColumnName(i);
columnDistinctHLL.computeIfAbsent(colName,
k -> HyperLogLog.builder().withPrecision(10).build())
.add(value.getBytes());
}
}
}
public long estimateDistinct(String column) {
return columnDistinctHLL.getOrDefault(column,
HyperLogLog.builder().withPrecision(10).build())
.cardinality();
}
}
和其他方案比一比,HyperLogLog的优势就非常明显了:内存占用断崖式下降,虽然有几个点的误差,但完全在可接受范围内。
| 方案 | 内存占用 | 误差率 | 适用数据量 | 实现复杂度 |
|---|---|---|---|---|
| HashSet | O(n) 巨大 | 0% | <10万 | 低 |
| Bloom Filter | ~1MB/百万 | 0.1%假阳性 | 任意 | 中 |
| HyperLogLog(精度12) | 4KB | ~3% | >10万 | 中 |
| HyperLogLog(精度14) | 16KB | ~2% | >100万 | 中 |
| HyperLogLog(精度16) | 64KB | ~1.5% | >1000万 | 中 |
精度选择可以直接根据预估数据量来确定,省心又稳妥。
// 根据数据量选择精度
public class HLLFactory {
public static HyperLogLog create(long estimatedSize) {
int precision;
if (estimatedSize < 100_000) precision = 12;
else if (estimatedSize < 10_000_000) precision = 14;
else precision = 16;
return HyperLogLog.builder().withPrecision(precision).build();
}
}
在分布式系统里,多个服务节点分别统计,最后把结果合并就能得到全局的基数估算。
// 多个服务节点各自统计,最后合并
public class DistributedHLL {
public long mergeAndCount(List serializedHLLs) {
HyperLogLog merged = HyperLogLog.builder()
.withPrecision(14)
.build();
for (byte[] data : serializedHLLs) {
HyperLogLog hll = HyperLogLog.fromBytes(data);
merged.merge(hll); // Gua va支持merge
}
return merged.cardinality();
}
}
最后,有几个关键点必须心里有数:
总而言之,HyperLogLog是处理超大规模去重统计的利器。在日活统计、UV分析、数据仓库等场景里,它用KB级的内存就解决了TB级数据的去重问题,性价比极高。当然,碰到需要精确计数的场景,还是得老老实实回到传统精确去重方案上。