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