Ping.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. <?php
  2. namespace app\webscoket;
  3. use think\facade\Cache;
  4. /**
  5. * Class Ping
  6. * @package app\webscoket
  7. * @author zfy
  8. * @day 2020-04-29
  9. */
  10. class Ping
  11. {
  12. /**
  13. * @var \Redis
  14. */
  15. protected $redis;
  16. const CACHE_PINK_KEY = 'ws.p.';
  17. const CACHE_SET_KEY = 'ws.s';
  18. /**
  19. * Ping constructor.
  20. */
  21. public function __construct()
  22. {
  23. $this->redis = Cache::store('redis')->handler();
  24. $this->destroy();
  25. }
  26. /**
  27. * @param $id
  28. * @param $time
  29. * @param int $timeout
  30. * @author zfy
  31. * @day 2020-04-29
  32. */
  33. public function createPing($id, $time, $timeout = 0)
  34. {
  35. $this->updateTime($id, $time, $timeout);
  36. $this->redis->sAdd(self::CACHE_SET_KEY, $id);
  37. }
  38. /**
  39. * @param $id
  40. * @param $time
  41. * @param int $timeout
  42. * @author zfy
  43. * @day 2020-04-29
  44. */
  45. public function updateTime($id, $time, $timeout = 0)
  46. {
  47. $this->redis->set(self::CACHE_PINK_KEY . $id, $time, $timeout);
  48. }
  49. /**
  50. * @param $id
  51. * @author zfy
  52. * @day 2020-05-06
  53. */
  54. public function removePing($id)
  55. {
  56. $this->redis->del(self::CACHE_PINK_KEY . $id);
  57. $this->redis->del(self::CACHE_SET_KEY, $id);
  58. }
  59. /**
  60. * @param $id
  61. * @return bool|string
  62. * @author zfy
  63. * @day 2020-04-29
  64. */
  65. public function getLastTime($id)
  66. {
  67. return $this->redis->get(self::CACHE_PINK_KEY . $id);
  68. }
  69. /**
  70. * @author zfy
  71. * @day 2020-04-29
  72. */
  73. public function destroy()
  74. {
  75. $members = $this->redis->sMembers(self::CACHE_SET_KEY) ?: [];
  76. foreach ($members as $k => $member) {
  77. $members[$k] = self::CACHE_PINK_KEY . $member;
  78. }
  79. if (count($members))
  80. $this->redis->del(self::CACHE_SET_KEY, ...$members);
  81. }
  82. }