CacheService.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  8. // +----------------------------------------------------------------------
  9. // | Author: CRMEB Team <admin@crmeb.com>
  10. // +----------------------------------------------------------------------
  11. namespace crmeb\services;
  12. use think\facade\Cache as CacheStatic;
  13. /**
  14. * crmeb 缓存类
  15. * Class CacheService
  16. * @package crmeb\services
  17. * @mixin \Redis
  18. */
  19. class CacheService
  20. {
  21. //副屏相关
  22. const CASHIER_AUX_SCREEN_TAG = 'auxScreen';
  23. /**
  24. * 标签名
  25. * @var string
  26. */
  27. protected static $globalCacheName = '_cached_1515146130';
  28. /**
  29. * 缓存队列key
  30. * @var string[]
  31. */
  32. protected static $redisQueueKey = [
  33. 0 => 'product',
  34. 1 => 'seckill',
  35. 2 => 'bargain',
  36. 3 => 'combination',
  37. 4 => 'integral',
  38. 5 => 'discounts',
  39. 6 => 'lottery'
  40. ];
  41. /**
  42. * 过期时间
  43. * @var int
  44. */
  45. protected static $expire;
  46. /**
  47. * 获取缓存过期时间
  48. * @param int|null $expire
  49. * @return int
  50. */
  51. protected static function getExpire(int $expire = null): int
  52. {
  53. if (self::$expire) {
  54. return (int)self::$expire;
  55. }
  56. $expire = !is_null($expire) ? $expire : SystemConfigService::get('cache_config', null, true);
  57. if (!is_int($expire))
  58. $expire = (int)$expire;
  59. return self::$expire = $expire;
  60. }
  61. /**
  62. * 判断缓存是否存在
  63. * @param string $name
  64. * @return bool
  65. * @throws \Psr\SimpleCache\InvalidArgumentException
  66. */
  67. public static function has(string $name): bool
  68. {
  69. try {
  70. return CacheStatic::has($name);
  71. } catch (\Throwable $e) {
  72. return false;
  73. }
  74. }
  75. /**
  76. * 写入缓存
  77. * @param string $name 缓存名称
  78. * @param mixed $value 缓存值
  79. * @param int $expire 缓存时间,为0读取系统缓存时间
  80. * @return bool
  81. */
  82. public static function set(string $name, $value, int $expire = null): bool
  83. {
  84. try {
  85. return self::handler()->set($name, $value, $expire ?? self::getExpire($expire));
  86. } catch (\Throwable $e) {
  87. return false;
  88. }
  89. }
  90. /**
  91. * 如果不存在则写入缓存
  92. * @param string $name
  93. * @param bool $default
  94. * @return mixed
  95. */
  96. public static function get(string $name, $default = false, int $expire = null)
  97. {
  98. try {
  99. return self::handler()->remember($name, $default, $expire ?? self::getExpire($expire));
  100. } catch (\Throwable $e) {
  101. try {
  102. if (is_callable($default)) {
  103. return $default();
  104. } else {
  105. return $default;
  106. }
  107. } catch (\Throwable $e) {
  108. return null;
  109. }
  110. }
  111. }
  112. /**
  113. * 如果不存在则写入缓存
  114. * @param string $name
  115. * @param bool $default
  116. * @return mixed
  117. */
  118. public static function remember(string $name, $default = false, int $expire = null)
  119. {
  120. try {
  121. return self::handler()->remember($name, $default, $expire ?? self::getExpire($expire));
  122. } catch (\Throwable $e) {
  123. try {
  124. if (is_callable($default)) {
  125. return $default();
  126. } else {
  127. return $default;
  128. }
  129. } catch (\Throwable $e) {
  130. return null;
  131. }
  132. }
  133. }
  134. /**
  135. * 删除缓存
  136. * @param string $name
  137. * @return bool
  138. * @throws \Psr\SimpleCache\InvalidArgumentException
  139. */
  140. public static function delete(string $name)
  141. {
  142. return CacheStatic::delete($name);
  143. }
  144. /**
  145. * 缓存句柄
  146. *
  147. * @return \think\cache\TagSet|CacheStatic
  148. */
  149. public static function handler(?string $cacheName = null)
  150. {
  151. return CacheStatic::tag($cacheName ?: self::$globalCacheName);
  152. }
  153. /**
  154. * 清空缓存池
  155. * @return bool
  156. */
  157. public static function clear()
  158. {
  159. return self::handler()->clear();
  160. }
  161. /**
  162. * Redis缓存句柄
  163. *
  164. * @return \think\cache\TagSet|CacheStatic
  165. */
  166. public static function redisHandler(string $type = null)
  167. {
  168. if ($type) {
  169. return CacheStatic::store('redis')->tag($type);
  170. } else {
  171. return CacheStatic::store('redis');
  172. }
  173. }
  174. /**
  175. * 放入令牌桶
  176. * @param string $key
  177. * @param array $value
  178. * @param string $type
  179. * @return bool
  180. */
  181. public static function setTokenBucket(string $key, $value, $expire = null, string $type = 'admin')
  182. {
  183. try {
  184. $redisCahce = self::redisHandler($type);
  185. return $redisCahce->set($key, $value, $expire);
  186. } catch (\Throwable $e) {
  187. return false;
  188. }
  189. }
  190. /**
  191. * 清除所有令牌桶
  192. * @param string $type
  193. * @return bool
  194. */
  195. public static function clearTokenAll(string $type = 'admin')
  196. {
  197. try {
  198. return self::redisHandler($type)->clear();
  199. } catch (\Throwable $e) {
  200. return false;
  201. }
  202. }
  203. /**
  204. * 清除令牌桶
  205. * @param string $type
  206. * @return bool
  207. */
  208. public static function clearToken(string $key)
  209. {
  210. try {
  211. return self::redisHandler()->delete($key);
  212. } catch (\Throwable $e) {
  213. return false;
  214. }
  215. }
  216. /**
  217. * 查看令牌是否存在
  218. * @param string $key
  219. * @return bool
  220. */
  221. public static function hasToken(string $key)
  222. {
  223. try {
  224. return self::redisHandler()->has($key);
  225. } catch (\Throwable $e) {
  226. return false;
  227. }
  228. }
  229. /**
  230. * 获取token令牌桶
  231. * @param string $key
  232. * @return mixed|null
  233. * @throws \Psr\SimpleCache\InvalidArgumentException
  234. */
  235. public static function getTokenBucket(string $key)
  236. {
  237. try {
  238. return self::redisHandler()->get($key, null);
  239. } catch (\Throwable $e) {
  240. return null;
  241. }
  242. }
  243. /**
  244. * 获取指定分数区间的成员
  245. * @param $key
  246. * @param int $start
  247. * @param int $end
  248. * @param array $options
  249. * @return mixed
  250. */
  251. public static function zRangeByScore($key, $start = '-inf', $end = '+inf', array $options = [])
  252. {
  253. return self::redisHandler()->zRangeByScore($key, $start, $end, $options);
  254. }
  255. /**
  256. * 设置redis入库队列
  257. * @param string $unique
  258. * @param int $number
  259. * @param int $type
  260. * @param bool $isPush true :重置 false:累加
  261. * @return bool
  262. */
  263. public static function setStock(string $unique, int $number, int $type = 1, bool $isPush = true)
  264. {
  265. if (!$unique || !$number) return false;
  266. $name = (self::$redisQueueKey[$type] ?? '') . '_' . $type . '_' . $unique;
  267. /** @var self $cache */
  268. $cache = self::redisHandler();
  269. $res = true;
  270. if ($isPush) {
  271. $cache->del($name);
  272. }
  273. $data = [];
  274. for ($i = 1; $i <= $number; $i++) {
  275. $data[] = $i;
  276. }
  277. $res = $res && $cache->lPush($name, ...$data);
  278. return $res;
  279. }
  280. /**
  281. * 弹出redis队列中的库存条数
  282. * @param string $unique
  283. * @param int $number
  284. * @param int $type
  285. * @return bool
  286. */
  287. public static function popStock(string $unique, int $number, int $type = 1)
  288. {
  289. if (!$unique || !$number) return false;
  290. $name = (self::$redisQueueKey[$type] ?? '') . '_' . $type . '_' . $unique;
  291. /** @var self $cache */
  292. $cache = self::redisHandler();
  293. $res = true;
  294. if ($number > $cache->lLen($name)) {
  295. return false;
  296. }
  297. for ($i = 1; $i <= $number; $i++) {
  298. $res = $res && $cache->lPop($name);
  299. }
  300. return $res;
  301. }
  302. /**
  303. * 是否有库存|返回库存
  304. * @param string $unique
  305. * @param int $number
  306. * @param int $type
  307. * @return bool
  308. */
  309. public static function checkStock(string $unique, int $number = 0, int $type = 1)
  310. {
  311. $name = (self::$redisQueueKey[$type] ?? '') . '_' . $type . '_' . $unique;
  312. if ($number) {
  313. return self::redisHandler()->lLen($name) >= $number;
  314. } else {
  315. return self::redisHandler()->lLen($name);
  316. }
  317. }
  318. /**
  319. * 检查锁
  320. * @param int $uid
  321. * @param int $timeout
  322. * @return bool
  323. * @author 等风来
  324. * @email 136327134@qq.com
  325. * @date 2022/11/22
  326. */
  327. public static function setMutex(string $key, int $timeout = 10)
  328. {
  329. $curTime = time();
  330. $readMutexKey = "redis:mutex:{$key}";
  331. $mutexRes = self::redisHandler()->handler()->setnx($readMutexKey, $curTime + $timeout);
  332. if ($mutexRes) {
  333. return true;
  334. }
  335. //就算意外退出,下次进来也会检查key,防止死锁
  336. $time = self::redisHandler()->handler()->get($readMutexKey);
  337. if ($curTime > $time) {
  338. self::redisHandler()->handler()->del($readMutexKey);
  339. return self::redisHandler()->handler()->setnx($readMutexKey, $curTime + $timeout);
  340. }
  341. return false;
  342. }
  343. /**
  344. * 删除锁
  345. * @param $uid
  346. * @author 等风来
  347. * @email 136327134@qq.com
  348. * @date 2022/11/22
  349. */
  350. public static function delMutex(string $key)
  351. {
  352. $readMutexKey = "redis:mutex:{$key}";
  353. self::redisHandler()->handler()->del($readMutexKey);
  354. }
  355. /**
  356. * 魔术方法
  357. * @param $name
  358. * @param $arguments
  359. * @return mixed
  360. */
  361. public static function __callStatic($name, $arguments)
  362. {
  363. return self::redisHandler()->{$name}(...$arguments);
  364. }
  365. /**
  366. * 魔术方法
  367. * @param $name
  368. * @param $arguments
  369. * @return mixed
  370. */
  371. public function __call($name, $arguments)
  372. {
  373. return self::redisHandler()->{$name}(...$arguments);
  374. }
  375. }