Fight a lot of background development Zhenti interview: How Statistics unique visitors with Redis

 


 

The congregation weeks to fight a lot of terrible treatment is high, in terms of poaching also spared no effort for three years to develop some of the work, a little bit of good, gave 30K to the Offer, as of course, is also known to fight a lot of overtime, the classes six days a week is the norm, basic daily working time is more than 12 hours, is quite hard. Ado, today we chat a lot of fight in a backstage interview Zhenti, is a simple subject architecture class: fight a lot of hundreds of millions of users, then for a page, how to use Redis statistics of a website the number of users accessing it?

Use Hash

Hash is a basic data structure of Redis, Redis is an open-bottom maintenance hash, it will be mapped to a different key on the hash table, if the keyword is experiencing conflict, it will pull out a list out.

When a user visits, if the user login too, then we use the user id, if the user is not logged in before, then we can front page a randomly generated key is used to identify the user, when the user time of the visit, I can use HSET command, key corresponding to the URI can be selected patchwork date, field id of the user may be used or a random identification, value may simply be set to 1.

When we want to count one day of a particular website visits when , can be used directly HLEN to get the final result.


 

Pros: Simple, easy to implement, is also very convenient inquiry, data accuracy is very high.

Disadvantages: take up too much memory. With the increase key, the performance will fall. Small OK, a lot of this fight certainly can not stand the site of hundreds of millions of PV

Use Bitset

我们知道,对于一个32位的int,如果我们只用来记录id,那么只能够记录一个用户,但如果我们转成2进制,每位用来表示一个用户,那么我们就能够一口气表示32个用户,空间节省了32倍!对于有大量数据的场景,如果我们使用bitset,那么,可以节省非常多的内存。对于没有登陆的用户,我们也可以使用哈希算法,把对应的用户标识哈希成一个数字id。bitset非常的节省内存,假设有1亿个用户,也只需要100000000/8/1024/1024约等于12兆内存。


 

Redis已经为我们提供了SETBIT的方法,使用起来非常的方便,我们可以看看下面的例子,我们在item页面可以不停地使用SETBIT命令,设置用户已经访问了该页面,也可以使用GETBIT的方法查询某个用户是否访问。最后我们通过BITCOUNT可以统计该网页每天的访问数量。


 

优点占用内存更小,查询方便,可以指定查询某个用户,数据可能略有瑕疵,对于非登陆的用户,可能不同的key映射到同一个id,否则需要维护一个非登陆用户的映射,有额外的开销。

缺点如果用户非常的稀疏,那么占用的内存可能比方法一更大。

使用概率算法

对于拼多多这种多个页面都可能非常多访问量的网站,如果所需要的数量不用那么准确,可以使用概率算法,事实上,我们对一个网站的UV的统计,1亿跟1亿零30万其实是差不多的。在Redis中,已经封装了HyperLogLog算法,他是一种基数评估算法。这种算法的特征,一般都是数据不存具体的值,而是存用来计算概率的一些相关数据。


 

当用户访问网站的时候,我们可以使用PFADD命令,设置对应的命令,最后我们只要通过PFCOUNT就能顺利计算出最终的结果,因为这个只是一个概率算法,所以可能存在0.81%的误差。

优点占用内存极小,对于一个key,只需要12kb。对于拼多多这种超多用户的特别适用。

缺点查询指定用户的时候,可能会出错,毕竟存的不是具体的数据。总数也存在一定的误差。

好了,上面就是常见的3种适用Redis统计网站用户访问数的方法了。

扩展阅读

MySQL 在并发场景下的问题及解决思路

阿里淘宝双十一秒杀系统设计详解

40个好的用户界面-界面设计的一些技巧

JavaWeb之ServletContext——统计用户访问网站次数

15个顶级Java多线程面试题及回答

作者:沙茶敏碎碎念

来源:https://www.toutiao.com/a6695734985246114312/

Guess you like

Origin www.cnblogs.com/javafirst0/p/11163955.html