Ping.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace app\webscoket;
  12. use think\facade\Cache;
  13. /**
  14. * Class Ping
  15. * @package app\webscoket
  16. * @author xaboy
  17. * @day 2020-04-29
  18. */
  19. class Ping
  20. {
  21. /**
  22. * @var \Redis
  23. */
  24. protected $redis;
  25. const CACHE_PINK_KEY = 'ws.p.';
  26. const CACHE_SET_KEY = 'ws.s';
  27. /**
  28. * Ping constructor.
  29. */
  30. public function __construct()
  31. {
  32. $this->redis = Cache::store('redis')->handler();
  33. $this->destroy();
  34. }
  35. /**
  36. * @param $id
  37. * @param $time
  38. * @param int $timeout
  39. * @author xaboy
  40. * @day 2020-04-29
  41. */
  42. public function createPing($id, $time, $timeout = 0)
  43. {
  44. $this->updateTime($id, $time, $timeout);
  45. $this->redis->sAdd(self::CACHE_SET_KEY, $id);
  46. }
  47. /**
  48. * @param $id
  49. * @param $time
  50. * @param int $timeout
  51. * @author xaboy
  52. * @day 2020-04-29
  53. */
  54. public function updateTime($id, $time, $timeout = 0)
  55. {
  56. $this->redis->set(self::CACHE_PINK_KEY . $id, $time, $timeout);
  57. }
  58. /**
  59. * @param $id
  60. * @author xaboy
  61. * @day 2020-05-06
  62. */
  63. public function removePing($id)
  64. {
  65. $this->redis->del(self::CACHE_PINK_KEY . $id);
  66. $this->redis->del(self::CACHE_SET_KEY, $id);
  67. }
  68. /**
  69. * @param $id
  70. * @return bool|string
  71. * @author xaboy
  72. * @day 2020-04-29
  73. */
  74. public function getLastTime($id)
  75. {
  76. return $this->redis->get(self::CACHE_PINK_KEY . $id);
  77. }
  78. /**
  79. * @author xaboy
  80. * @day 2020-04-29
  81. */
  82. public function destroy()
  83. {
  84. $members = $this->redis->sMembers(self::CACHE_SET_KEY) ?: [];
  85. foreach ($members as $k => $member) {
  86. $members[$k] = self::CACHE_PINK_KEY . $member;
  87. }
  88. if (count($members))
  89. $this->redis->del(self::CACHE_SET_KEY, ...$members);
  90. }
  91. }