App_Service_RedisService.proxy.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Service;
  3. use App\Cache\SocketFdBindUser;
  4. use App\Cache\SocketUserBindFds;
  5. /**
  6. * websocket关系存储
  7. *
  8. * @package App\Service
  9. */
  10. class RedisService extends RedisInterface
  11. {
  12. use \Hyperf\Di\Aop\ProxyTrait;
  13. use \Hyperf\Di\Aop\PropertyHandlerTrait;
  14. function __construct()
  15. {
  16. if (method_exists(parent::class, '__construct')) {
  17. parent::__construct(...func_get_args());
  18. }
  19. $this->__handlePropertyHandler(__CLASS__);
  20. }
  21. protected $prefix_fn = 'chat_fn';
  22. protected $prefix_user = 'chat_user';
  23. /**
  24. * 绑定fd和用户关系
  25. * @param string $fid
  26. * @param int $userId
  27. * @param $run_id
  28. * @return void
  29. * @throws \RedisException
  30. */
  31. public function bind(string $fid, int $userId, $run_id = SERVER_RUN_ID)
  32. {
  33. //站点通道+用户
  34. $this->redis->hSet($run_id, $this->prefix_fn . $fid, $userId);
  35. //站点用户+通道
  36. $this->redis->hSet($run_id, $this->prefix_user . $userId, $fid);
  37. }
  38. /**
  39. * 解绑通道和用户关系
  40. * @param string $fid
  41. * @param int $userId
  42. * @param $run_id
  43. * @return void
  44. * @throws \RedisException
  45. */
  46. public function unbind(string $fid, int $userId, $run_id = SERVER_RUN_ID)
  47. {
  48. $this->redis->hDel($run_id, $this->prefix_fn . $fid);
  49. $this->redis->hDel($run_id, $this->prefix_user . $userId);
  50. }
  51. /**
  52. * 通过FD获取userID
  53. * @param string $fid
  54. * @param $run_id
  55. * @return false|\Redis|string
  56. * @throws \RedisException
  57. */
  58. public function findUser(string $fid, $run_id = SERVER_RUN_ID)
  59. {
  60. return $this->redis->hGet($run_id, $this->prefix_fn . $fid);
  61. }
  62. /**
  63. * 通过UserID 获取fd
  64. * @param int $userId
  65. * @param $run_id
  66. * @return false|\Redis|string
  67. * @throws \RedisException
  68. */
  69. public function findFd(int $userId, $run_id = SERVER_RUN_ID)
  70. {
  71. return $this->redis->hGet($run_id, $this->prefix_user . $userId);
  72. }
  73. }