PHP統計線上使用者數量

來源:互聯網
上載者:User

標籤:儲存   struct   attach   php   ++   日期   首碼   func   online   

一段經典的php統計線上使用者數量的代碼,一起學習分享。

  1. <?php
  2. /**
  3.  * Created by PhpStorm.
  4.  * User: jifei
  5.  * Date: 15/11/24
  6.  * Time: 20:58
  7.  *
  8.  * 每分鐘百萬使用者,即時統計最近15分鐘線上使用者總數
  9.  */
  10. class OnlineUser
  11. {
  12.     public $prefix_key = "online";//key首碼
  13.     public function __construct()
  14.     {
  15.         $this->redis = new Redis();
  16.     }
  17.     /**
  18.      * 往集合中添加新的線上使用者
  19.      *
  20.      * @param $uid
  21.      */
  22.     public function addUser($uid)
  23.     {
  24.         $this->redis->sAdd($this->prefix_key . date(‘hi‘), $uid);
  25.     }
  26.     /**
  27.      * 擷取線上使用者數
  28.      *
  29.      * @param $start_min  統計開始分鐘 hi格式
  30.      * @param $end_min    統計結束的分鐘
  31.      *
  32.      * @return mixed
  33.      */
  34.     public function userNum($start_min, $end_min)
  35.     {
  36.         //第一個參數,並集的key名稱
  37.         $params[] = $this->prefix_key . $start_min . ‘_‘ . $end_min;
  38.         //遍曆時間區間內所有的分鐘,並放入到參數中
  39.         for ($min = $start_min; $min < $end_min; $min++) {
  40.             $params[] = $this->prefix_key . $min;
  41.         }
  42.         //求所有分鐘的使用者的並集並儲存,效能比直接計算返回快很多,省去了資料轉送
  43.         $num = call_user_func_array([$this->redis, "sUnionStore"], $params);
  44.         //刪除臨時並集
  45.         $this->redis->delete($params[0]);
  46.         return $num;
  47.     }
  48. }
   

發布日期: 2016-07-30  511遇見

所屬分類: Php 標籤: Php

PHP統計線上使用者數量

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.