Ping.php 1.9 KB

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