Redis.php 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // |
  4. // +----------------------------------------------------------------------
  5. // |
  6. // +----------------------------------------------------------------------
  7. // |
  8. // +----------------------------------------------------------------------
  9. // |
  10. // +----------------------------------------------------------------------
  11. namespace app\common\library\token\driver;
  12. use app\common\library\token\Driver;
  13. /**
  14. * Redis缓存驱动,适合单机部署、有前端代理实现高可用的场景,性能最好
  15. * 有需要在业务层实现读写分离、或者使用RedisCluster的需求,请使用Redisd驱动
  16. *
  17. * 要求安装phpredis扩展:https://github.com/nicolasff/phpredis
  18. * @author 尘缘 <130775@qq.com>
  19. */
  20. class Redis extends Driver
  21. {
  22. protected $options = [
  23. 'host' => '127.0.0.1',
  24. 'port' => 6379,
  25. 'password' => '',
  26. 'select' => 0,
  27. 'timeout' => 0,
  28. 'expire' => 0,
  29. 'persistent' => false,
  30. 'userprefix' => 'up:',
  31. 'tokenprefix' => 'tp:',
  32. ];
  33. /**
  34. * 构造函数
  35. * @param array $options 缓存参数
  36. * @throws \RedisException
  37. */
  38. public function __construct(array $options = [])
  39. {
  40. if (!extension_loaded('redis')) {
  41. throw new \BadFunctionCallException('not support: redis');
  42. }
  43. if (!empty($options)) {
  44. $this->options = array_merge($this->options, $options);
  45. }
  46. $this->handler = new \Redis;
  47. if ($this->options['persistent']) {
  48. $this->handler->pconnect($this->options['host'], $this->options['port'], $this->options['timeout'], 'persistent_id_' . $this->options['select']);
  49. } else {
  50. $this->handler->connect($this->options['host'], $this->options['port'], $this->options['timeout']);
  51. }
  52. if ('' != $this->options['password']) {
  53. $this->handler->auth($this->options['password']);
  54. }
  55. if (0 != $this->options['select']) {
  56. $this->handler->select($this->options['select']);
  57. }
  58. }
  59. /**
  60. * 获取加密后的Token
  61. * @param string $token Token标识
  62. * @return string
  63. */
  64. protected function getEncryptedToken(string $token): string
  65. {
  66. $config = \think\facade\Config::get('token');
  67. return $this->options['tokenprefix'] . hash_hmac($config['hashalgo'], $token, $config['key']);
  68. }
  69. /**
  70. * 获取会员的key
  71. * @param int $user_id
  72. * @return string
  73. */
  74. protected function getUserKey(int $user_id): string
  75. {
  76. return $this->options['userprefix'] . $user_id;
  77. }
  78. /**
  79. * 存储Token
  80. * @param string $token Token
  81. * @param int $user_id 会员ID
  82. * @param int $expire 过期时长,0表示无限,单位秒
  83. * @return bool|\Redis
  84. * @throws \RedisException
  85. */
  86. public function set(string $token, int $user_id, $expire = 0)
  87. {
  88. if (is_null($expire)) {
  89. $expire = $this->options['expire'];
  90. }
  91. if ($expire instanceof \DateTime) {
  92. $expire = $expire->getTimestamp() - time();
  93. }
  94. $key = $this->getEncryptedToken($token);
  95. if ($expire) {
  96. $result = $this->handler->setex($key, $expire, $user_id);
  97. } else {
  98. $result = $this->handler->set($key, $user_id);
  99. }
  100. //写入会员关联的token
  101. $this->handler->sAdd($this->getUserKey($user_id), $key);
  102. return $result;
  103. }
  104. /**
  105. * 获取Token内的信息
  106. * @param string $token $token
  107. * @return array
  108. * @throws \RedisException
  109. */
  110. public function get(string $token): array
  111. {
  112. $key = $this->getEncryptedToken($token);
  113. $value = $this->handler->get($key);
  114. if (is_null($value) || false === $value) {
  115. return [];
  116. }
  117. //获取有效期
  118. $expire = $this->handler->ttl($key);
  119. $expire = $expire < 0 ? 365 * 86400 : $expire;
  120. $expiretime = time() + $expire;
  121. //解决使用redis方式储存token时api接口Token刷新与检测因expires_in拼写错误报错的BUG
  122. return ['token' => $token, 'user_id' => $value, 'expiretime' => $expiretime, 'expires_in' => $expire];
  123. }
  124. /**
  125. * 判断Token是否可用
  126. * @param string $token Token
  127. * @param int $user_id 会员ID
  128. * @return bool
  129. * @throws \RedisException
  130. */
  131. public function check(string $token, int $user_id): bool
  132. {
  133. $data = self::get($token);
  134. return $data && $data['user_id'] == $user_id;
  135. }
  136. /**
  137. * 删除Token
  138. * @param string $token
  139. * @return true
  140. * @throws \RedisException
  141. */
  142. public function delete(string $token): bool
  143. {
  144. $data = $this->get($token);
  145. if ($data) {
  146. $key = $this->getEncryptedToken($token);
  147. $user_id = $data['user_id'];
  148. $this->handler->del($key);
  149. $this->handler->sRem($this->getUserKey($user_id), $key);
  150. }
  151. return true;
  152. }
  153. /**
  154. * 删除指定用户的所有Token
  155. * @param int $user_id
  156. * @return true
  157. * @throws \RedisException
  158. */
  159. public function clear(int $user_id): bool
  160. {
  161. $keys = $this->handler->sMembers($this->getUserKey($user_id));
  162. $this->handler->del($this->getUserKey($user_id));
  163. $this->handler->del($keys);
  164. return true;
  165. }
  166. }