For example, if you want to display the total number of views of all sub-items under a category, it is impossible to count it once a user visits it. It is too resource-intensive. Please give me some advice on how to count it again after a period of time
For example, if you want to display the total number of views of all sub-items under a category, it is impossible to count it once a user visits it. It is too resource-intensive. Please give me some advice on how to count it again after a period of time
<code class="php">$redis = new redis(); $pv = "select pv from views where id={$id}";//第一次的pv值 $num = 100;// 累计100更新数据库 $incrPv = $redis->incr('pv:'.$id); if ($incrPv % $num === 0) { $sql = "update views set pv=pv+{$num} where id = {$id}"; } else if ($incrPv == 1) { $incrPv = $pv + 1; $redis->set('pv:'.$id, $incrPv); } </code>
Write a timing script to count old data
To count the number of views, you can use redis for caching
Real-time statistics are written to redis or other nosql databases, and crontab calculates and clears the nosql regularly
Execute PHP code online
It’s very simple, just set up the cache where you set the view count of the sub-items under the corresponding category.
For example, let me give you this example:
<code>// 这个方法是你说的统计一个父类下对应所有子类的浏览量的综合,`$time`是设置的缓存时间 function getCategoryNum($categoryId, $time=3600){ // 根据父类id统计所有子类的浏览量 } // 这个是每次访问时统计到你数据库或者缓存的地方的方法。这个方法是不用设置缓存的,因为每次都要做统计 function getViewsNum(){ // 用户访问浏览量+1操作 }</code>
The cache time is set through the above getCategoryNum()
method. The database will not be requested during the cache time. Only when the time is up will the database be requested to obtain the latest statistics. This is based on the time you set. .
How to set up cache that you should have in your project! If you want to do scheduled tasks, I think it's a bit wasteful. Of course, I am not sure of your specific business needs. Everything is subject to your business needs. Hope it helps you
If you do not plan to use other caching technologies, you can use mysql for caching. The cache structure is roughly Key, Value, and the last update time. If it exceeds this time, it will be updated. It should be noted that it needs to be considered when writing. Whether to verify the consistency of the written version