RedisUtil.php 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. <?php
  2. namespace App\Utils;
  3. use Hyperf\Config\Annotation\Value;
  4. use Hyperf\Context\ApplicationContext;
  5. use Hyperf\Coroutine\Coroutine;
  6. /**
  7. * 全局redis键值配置
  8. */
  9. class RedisUtil
  10. {
  11. /**
  12. * 注解
  13. * 设置redis前缀与框架保持一致
  14. *
  15. * @var string
  16. */
  17. #[Value("cache.default.prefix")]
  18. private $Key;
  19. private $Redis;
  20. private static $instances = [];
  21. /**
  22. * @param string $key
  23. * @param string $dynamic 动态拼接key//示例 RedisUtil::getInstance('key','user_no'); 则代表着 用户编号唯一的key
  24. * @throws \Exception
  25. */
  26. public function __construct(string $key)
  27. {
  28. $container = ApplicationContext::getContainer();
  29. $this->Redis = $container->get(\Redis::class);
  30. $this->Key = $this->Key . $key;
  31. }
  32. /**
  33. * @param string $key
  34. * @param string ...$dynamic key动态值拼接
  35. * @return RedisUtil|mixed
  36. * @throws \Exception
  37. */
  38. public static function getInstance(string $key, string ...$dynamic)
  39. {
  40. $dynamics = '';
  41. foreach ($dynamic as $k => $v) {
  42. if ($k == 0) {
  43. $dynamics .= $v;
  44. } else {
  45. $dynamics .= '_' . $v;
  46. }
  47. }
  48. $instanceName = Coroutine::id() . uniqid();//协程id&唯一id组成
  49. if (!isset(self::$instances[$instanceName])) {
  50. self::$instances[$instanceName] = new self($key . $dynamics);
  51. Coroutine::defer(function () use ($instanceName) {
  52. unset(self::$instances[$instanceName]);
  53. });
  54. }
  55. return self::$instances[$instanceName];
  56. }
  57. /**
  58. * 生成唯一标识
  59. * @param int $length 生成长度
  60. * @return string
  61. */
  62. public function createNo(int $length = 5): string
  63. {
  64. $redis = $this->Redis;
  65. $key = $this->Key;
  66. //指定键值新增+1 并获取
  67. $reqNo = $redis->incr($key);
  68. //值长度已达到5位,且首位已为9,初始化
  69. if (strlen($reqNo) >= $length && substr($reqNo, 0, 1) == 9) {
  70. $redis->set($key, 1);
  71. $reqNo = 1;
  72. }
  73. if ($reqNo == 1) {
  74. //设置月末到期
  75. $expire = strtotime(date('Y-m', strtotime("+1 month")) . '-01 00:00:00') - time();
  76. $redis->expire($key, $expire);
  77. }
  78. return sprintf("%0{$length}d", $reqNo);
  79. }
  80. /**
  81. * 限制接口请求次数
  82. * @param string $path 可以是路由,可以是地址,可以是ip,总之是 string 即可
  83. * @param int $second 秒
  84. * @param int $count 多长时间内限制请求次数
  85. * @return bool
  86. */
  87. public function requestLimit(string $path, int $second, int $count): bool
  88. {
  89. $redis = $this->Redis;
  90. $key = $this->Key . md5($path);
  91. /*$_cou = $redis->incr($key);
  92. if ($_cou > $count) return false;
  93. if ($_cou == 1) $redis->expire($key, $second);
  94. unset($redis, $_cou);
  95. return true;*/
  96. $luaScript = <<<lua
  97. local count = redis.call("incr",KEYS[1])
  98. if count == 1 then
  99. redis.call('expire',KEYS[1],ARGV[2])
  100. end
  101. if count > tonumber(ARGV[1]) then
  102. return 0
  103. end
  104. return 1
  105. lua;
  106. return (bool)$redis->eval($luaScript, [$key, $count, $second], 1);
  107. }
  108. /**
  109. * 限制尝试次数 (设定时间内)
  110. * @param int $second 秒
  111. * @param int $Times 次数
  112. * @return false|int
  113. */
  114. public function tryTimes(int $second, int $Times = 5)
  115. {
  116. $redis = $this->Redis;
  117. $key = $this->Key;
  118. //指定键值新增+1 并获取
  119. $count = $redis->incr($key);
  120. if ($count > $Times) {
  121. return false;
  122. }
  123. //设置过期时间
  124. if ($count == 1) {
  125. $redis->expire($key, $second);
  126. }
  127. return (int)$count;
  128. }
  129. /**
  130. * 加锁
  131. * @param int $timeout 锁的过期时间
  132. * @return false|string
  133. */
  134. public function Lock(int $timeout = 3)
  135. {
  136. $redis = $this->Redis;
  137. $lockName = $this->Key;//锁的名字
  138. #获取唯一标识符
  139. $identifier = uniqid();
  140. #锁的过期时间
  141. $end = time() + $timeout;
  142. #循环获取锁
  143. while (time() < $end) {
  144. #查看$lockName是否被上锁,为$lockName设置过期时间,防止死锁
  145. if ($redis->set($lockName, $identifier, ['ex' => $timeout, 'nx'])) {
  146. return $identifier;
  147. }
  148. #停止0.001ms
  149. usleep(0.001);
  150. }
  151. return false;
  152. }
  153. /**
  154. * 释放锁
  155. * @param string $identifier 锁的唯一值
  156. * @return bool
  157. */
  158. public function releaseLock(string $identifier): bool
  159. {
  160. $redis = $this->Redis;
  161. $lockName = $this->Key;//锁的名字
  162. // 判断是锁有没有被其他客户端修改
  163. if ($redis->get($lockName) != $identifier) {
  164. #其他客户端修改了锁,不能删除别人的锁
  165. return false;
  166. }
  167. #释放锁
  168. $redis->del($lockName);
  169. return true;
  170. }
  171. public function setex(string $value, int $second)
  172. {
  173. $redis = $this->Redis;
  174. $key = $this->Key;
  175. return $redis->setex($key, $second, $value);
  176. }
  177. public function get()
  178. {
  179. $redis = $this->Redis;
  180. $key = $this->Key;
  181. return $redis->get($key);
  182. }
  183. public function del()
  184. {
  185. $redis = $this->Redis;
  186. $key = $this->Key;
  187. return $redis->del($key);
  188. }
  189. //加入list
  190. public function lPush(array $value)
  191. {
  192. $redis = $this->Redis;
  193. $key = $this->Key;
  194. return $redis->lPush($key, $value);
  195. }
  196. //删除右边
  197. public function rPop()
  198. {
  199. $redis = $this->Redis;
  200. $key = $this->Key;
  201. return $redis->rPop($key);
  202. }
  203. //list长度
  204. public function lLen()
  205. {
  206. $redis = $this->Redis;
  207. $key = $this->Key;
  208. return $redis->llen($key);
  209. }
  210. public function zadd($score, $member)
  211. {
  212. $redis = $this->Redis;
  213. $key = $this->Key;
  214. return $redis->zadd($key, $score, $member);
  215. }
  216. public function zcard()
  217. {
  218. $redis = $this->Redis;
  219. $key = $this->Key;
  220. return $redis->zcard($key);
  221. }
  222. public function zrem($member)
  223. {
  224. $redis = $this->Redis;
  225. $key = $this->Key;
  226. return $redis->zrem($key, $member);
  227. }
  228. // 递增返回
  229. public function zRange($start_score = 0, $end_score = -1)
  230. {
  231. $redis = $this->Redis;
  232. $key = $this->Key;
  233. return $redis->zrange($key, $start_score, $end_score);
  234. }
  235. // 递减返回
  236. public function zRevRange($start_score = 0, $end_score = -1)
  237. {
  238. $redis = $this->Redis;
  239. $key = $this->Key;
  240. return $redis->zRevRange($key, $start_score, $end_score);
  241. }
  242. public function hSet($field, $value)
  243. {
  244. $redis = $this->Redis;
  245. $key = $this->Key;
  246. return $redis->hset($key, $field, $value);
  247. }
  248. public function hKeys()
  249. {
  250. $redis = $this->Redis;
  251. $key = $this->Key;
  252. return $redis->hkeys($key);
  253. }
  254. public function hGet($field)
  255. {
  256. $redis = $this->Redis;
  257. $key = $this->Key;
  258. return $redis->hget($key, $field);
  259. }
  260. public function hDel($field)
  261. {
  262. $redis = $this->Redis;
  263. $key = $this->Key;
  264. return $redis->hdel($key, $field);
  265. }
  266. public function incrby_expire($num,$second)
  267. {
  268. $redis = $this->Redis;
  269. $key = $this->Key;
  270. $count = $redis->incrby($key,$num);
  271. //设置过期时间
  272. $redis->expire($key, $second);
  273. return $count;
  274. }
  275. }