Heim  >  Artikel  >  Backend-Entwicklung  >  PHP统计在线用户数

PHP统计在线用户数

WBOY
WBOYOriginal
2016-07-25 08:42:171000Durchsuche
  1. /**
  2. * Created by PhpStorm.
  3. * User: jifei
  4. * Date: 15/11/24
  5. * Time: 20:58
  6. *
  7. * 每分钟百万用户,实时统计最近15分钟在线用户总数
  8. */
  9. class OnlineUser
  10. {
  11. public $prefix_key = "online";//key前缀
  12. public function __construct()
  13. {
  14. $this->redis = new Redis();
  15. }
  16. /**
  17. * 往集合中添加新的在线用户
  18. *
  19. * @param $uid
  20. */
  21. public function addUser($uid)
  22. {
  23. $this->redis->sAdd($this->prefix_key . date('hi'), $uid);
  24. }
  25. /**
  26. * 获取在线用户数
  27. *
  28. * @param $start_min 统计开始分钟 hi格式
  29. * @param $end_min 统计结束的分钟
  30. *
  31. * @return mixed
  32. */
  33. public function userNum($start_min, $end_min)
  34. {
  35. //第一个参数,并集的key名称
  36. $params[] = $this->prefix_key . $start_min . '_' . $end_min;
  37. //遍历时间区间内所有的分钟,并放入到参数中
  38. for ($min = $start_min; $min $params[] = $this->prefix_key . $min;
  39. }
  40. //求所有分钟的用户的并集并保存,性能比直接计算返回快很多,省去了数据传输
  41. $num = call_user_func_array([$this->redis, "sUnionStore"], $params);
  42. //删除临时并集
  43. $this->redis->delete($params[0]);
  44. return $num;
  45. }
  46. }
复制代码

PHP


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn