學 無 止 境 , 與 君 共 勉 。css
HyperLogLog
是Redis
中的高級數據結構,它主要用於對海量數據(能夠統計2^64個數據)作基數統計(去重統計數量)。它的特色是速度快,佔用空間小(12KB)。可是計算存會在偏差,標準偏差爲0.81%。HyperLogLog
只會根據輸入元素來計算基數,而不會儲存輸入元素自己,因此他並不能判斷給定的元素是否已經存在了。java
將指定的元素添加到HyperLogLog
中,能夠添加多個元素git
public void pfAdd(String key, String... value) {
stringRedisTemplate.opsForHyperLogLog().add(key, value);
}
複製代碼
返回給定HyperLogLog
的基數估算值。當一次統計多個HyperLogLog
時,須要對多個HyperLogLog
結構進行比較,並將並集的結果放入一個臨時的HyperLogLog
,性能不高,謹慎使用github
public Long pfCount(String... key) {
return stringRedisTemplate.opsForHyperLogLog().size(key);
}
複製代碼
將多個HyperLogLog
進行合併,將並集的結果放入一個指定的HyperLogLog中web
public void pfMerge(String destKey, String... sourceKey) {
stringRedisTemplate.opsForHyperLogLog().union(destKey, sourceKey);
}
複製代碼
基於SpringBoot的進行偏差測試,初始化5個HyperLogLog
,每一個隨機添加10000個元素,而後調用pfcount
查看具體偏差:redis
@RestController
@RequestMapping("/redis/hll")
public class HyperController {
private final RedisService redisService;
public HyperController(RedisService redisService) {
this.redisService = redisService;
}
@GetMapping("/init")
public String init() {
for (int i = 0; i < 5; i++) {
Thread thread = new Thread(() -> {
String name = Thread.currentThread().getName();
Random r = new Random();
int begin = r.nextInt(100) * 10000;
int end = begin + 10000;
for (int j = begin; j < end; j++) {
redisService.pfAdd("hhl:" + name, j + "");
}
System.out.printf("線程【%s】完成數據初始化,區間[%d, %d)\n", name, begin, end);
},
i + "");
thread.start();
}
return "success";
}
@GetMapping("/count")
public String count() {
long a = redisService.pfCount("hhl:0");
long b = redisService.pfCount("hhl:1");
long c = redisService.pfCount("hhl:2");
long d = redisService.pfCount("hhl:3");
long e = redisService.pfCount("hhl:4");
System.out.printf("hhl:0 -> count: %d, rate: %f\n", a, (10000 - a) * 1.00 / 100);
System.out.printf("hhl:1 -> count: %d, rate: %f\n", b, (10000 - b) * 1.00 / 100);
System.out.printf("hhl:2 -> count: %d, rate: %f\n", c, (10000 - c) * 1.00 / 100);
System.out.printf("hhl:3 -> count: %d, rate: %f\n", d, (10000 - d) * 1.00 / 100);
System.out.printf("hhl:4 -> count: %d, rate: %f\n", e, (10000 - e) * 1.00 / 100);
return "success";
}
}
複製代碼
初始化數據,調用接口:http://localhost:8080/redis/hll/init
spring
線程【4】完成數據初始化,區間[570000, 580000)
線程【2】完成數據初始化,區間[70000, 80000)
線程【0】完成數據初始化,區間[670000, 680000)
線程【1】完成數據初始化,區間[210000, 220000)
線程【3】完成數據初始化,區間[230000, 240000)
複製代碼
查看具體統計數,計算偏差:http://localhost:8080/redis/hll/count
apache
hhl:0 -> count: 10079, rate: -0.790000
hhl:1 -> count: 9974, rate: 0.260000
hhl:2 -> count: 10018, rate: -0.180000
hhl:3 -> count: 10053, rate: -0.530000
hhl:4 -> count: 9985, rate: 0.150000
複製代碼
好比要統計文章的熱度和有效用戶點擊數。能夠經過Reis的計數器來統計熱度,每次請就執行incr
指令。經過HyperLogLog
來統計有效用戶數。微信
經過AOP和自定義註解來對須要統計的文章進行統計:cookie
HyperLogLog
對應的key
引入redis
和aop
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- redis Lettuce 模式 鏈接池 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
複製代碼
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Article {
/**
* 值爲對應HyperLogLog的key
*/
String value() default "";
}
複製代碼
@Aspect
@Component
public class ArticleAop {
private static final String PV_PREFIX = "PV:";
private static final String UV_PREFIX = "UV:";
@Autowired
private RedisService redisService;
/**
* 定義切入點
*/
@Pointcut("@annotation(org.ylc.note.redis.hyperloglog.annotation.Article)")
private void statistics() {
}
@Around("statistics()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// 獲取註解
Method method = ((MethodSignature) proceedingJoinPoint.getSignature()).getMethod();
Article visitPermission = method.getAnnotation(Article.class);
String value = visitPermission.value();
// 獲取請求信息
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 這裏用來模擬,直接經過參數傳入。實際項目中能夠根據token或者cookie來實現
String userId = request.getParameter("userId");
// 熱度
redisService.incr(PV_PREFIX + value);
// 用戶量
redisService.pfAdd(UV_PREFIX + value, userId);
// 執行具體方法
return proceedingJoinPoint.proceed();
}
}
複製代碼
在須要統計的接口上加上@Article()
註解
@RestController
@RequestMapping("/redis/article")
public class ArticleController {
@Autowired
private RedisService redisService;
@Article("it")
@GetMapping("/it")
public String it(String userId) {
String pv = redisService.get("PV:it");
long uv = redisService.pfCount("UV:it");
return String.format("當前用戶:【%s】,當前it類熱度:【%s】,訪問用戶數:【%d】", userId, pv, uv);
}
@Article("news")
@GetMapping("/news")
public String news(String userId) {
String pv = redisService.get("PV:news");
long uv = redisService.pfCount("UV:news");
return String.format("當前用戶:【%s】,當前news類熱度:【%s】,訪問用戶數:【%d】", userId, pv, uv);
}
@GetMapping("/statistics")
public Object statistics() {
String pvIt = redisService.get("PV:it");
long uvIt = redisService.pfCount("UV:it");
String pvNews = redisService.get("PV:news");
long uvNews = redisService.pfCount("UV:news");
redisService.pfMerge("UV:merge", "UV:it", "UV:news");
long uvMerge = redisService.pfCount("UV:merge");
Map<String, String> result = new HashMap<>();
result.put("it", String.format("it類熱度:【%s】,訪問用戶數:【%d】;", pvIt, uvIt));
result.put("news", String.format("news類熱度:【%s】,訪問用戶數:【%d】", pvNews, uvNews));
result.put("merge", String.format("合併後訪問用戶數:【%d】", uvMerge));
return result;
}
}
複製代碼
全部代碼均上傳至Github上,方便你們訪問
>>>>>> Redis實戰 — HyperLogLog <<<<<<
創做不易,若是各位以爲有幫助,求點贊 支持
微信公衆號: 俞大仙