App_Service_RedisService.proxy.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. protected $prefix_user_info = 'userListInfo';
  24. /**
  25. * 绑定fd和用户关系
  26. * @param string $fid
  27. * @param int $userId
  28. * @param $run_id
  29. * @return void
  30. * @throws \RedisException
  31. */
  32. public function bind(string $fid, int $userId, $run_id = SERVER_RUN_ID)
  33. {
  34. //站点通道+用户
  35. $this->redis->hSet($run_id, $this->prefix_fn . $fid, $userId);
  36. //站点用户+通道
  37. $this->redis->hSet($run_id, $this->prefix_user . $userId, $fid);
  38. }
  39. /**
  40. * 解绑通道和用户关系
  41. * @param string $fid
  42. * @param int $userId
  43. * @param $run_id
  44. * @return void
  45. * @throws \RedisException
  46. */
  47. public function unbind(string $fid, int $userId, $run_id = SERVER_RUN_ID)
  48. {
  49. $this->redis->hDel($run_id, $this->prefix_fn . $fid);
  50. $this->redis->hDel($run_id, $this->prefix_user . $userId);
  51. }
  52. /**
  53. * 通过FD获取userID
  54. * @param string $fid
  55. * @param $run_id
  56. * @return false|\Redis|string
  57. * @throws \RedisException
  58. */
  59. public function findUser(string $fid, $run_id = SERVER_RUN_ID)
  60. {
  61. return $this->redis->hGet($run_id, $this->prefix_fn . $fid);
  62. }
  63. /**
  64. * 通过UserID 获取fd
  65. * @param int $userId
  66. * @param $run_id
  67. * @return false|\Redis|string
  68. * @throws \RedisException
  69. */
  70. public function findFd(int $userId, $run_id = SERVER_RUN_ID)
  71. {
  72. return $this->redis->hGet($run_id, $this->prefix_user . $userId);
  73. }
  74. /**
  75. * 存储用户信息
  76. * @param int $userId
  77. * @param array $data
  78. * @return void
  79. * @throws \RedisException
  80. */
  81. public function setUserInfo(string $userId, array $data)
  82. {
  83. $this->redis->hSet($this->prefix_user_info, $userId, json_encode($data));
  84. }
  85. /**
  86. * 获取用户信息
  87. * @param int $userId
  88. * @return void
  89. * @throws \RedisException
  90. */
  91. public function getUserInfo(string $userId)
  92. {
  93. $this->redis->hGet($this->prefix_user_info, $userId);
  94. }
  95. }