CacheDaoTrait.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. <?php
  2. /**
  3. * +----------------------------------------------------------------------
  4. * | CRMEB [ CRMEB赋能开发者,助力企业发展 ]
  5. * +----------------------------------------------------------------------
  6. * | Copyright (c) 2016~2022 https://www.crmeb.com All rights reserved.
  7. * +----------------------------------------------------------------------
  8. * | Licensed CRMEB并不是自由软件,未经许可不能去掉CRMEB相关版权
  9. * +----------------------------------------------------------------------
  10. * | Author: CRMEB Team <admin@crmeb.com>
  11. * +----------------------------------------------------------------------
  12. */
  13. namespace crmeb\traits\dao;
  14. use crmeb\services\CacheService;
  15. use crmeb\utils\Tag;
  16. use think\cache\TagSet;
  17. use think\Container;
  18. use think\facade\Log;
  19. use think\Model;
  20. /**
  21. * Trait CacheDaoTrait
  22. * @package crmeb\traits\dao
  23. * @method Model getModel()
  24. * @method Model getPk()
  25. */
  26. trait CacheDaoTrait
  27. {
  28. /**
  29. * 获取redis
  30. * @return \Redis
  31. * @author 等风来
  32. * @email 136327134@qq.com
  33. * @date 2022/10/29
  34. */
  35. private function getRedisConnect()
  36. {
  37. return CacheService::redisHandler()->handler();
  38. }
  39. /**
  40. * 获取缓存
  41. * @return TagSet|\think\facade\Cache
  42. * @author 等风来
  43. * @email 136327134@qq.com
  44. * @date 2022/11/10
  45. */
  46. private function getCacheHander()
  47. {
  48. return CacheService::redisHandler();
  49. }
  50. /**
  51. * 对外开放方法
  52. * @return TagSet|\think\facade\Cache
  53. * @author 等风来
  54. * @email 136327134@qq.com
  55. * @date 2022/11/10
  56. */
  57. public function cacheHander()
  58. {
  59. return $this->getCacheHander();
  60. }
  61. /**
  62. * 缓存标签
  63. * @param null $tag
  64. * @return Tag
  65. * @author 等风来
  66. * @email 136327134@qq.com
  67. * @date 2022/11/10
  68. */
  69. public function cacheTag($tag = null)
  70. {
  71. $key = $this->cacheKey() . 'tag';
  72. $tag = $tag ? $key . ':' . $tag : $key;
  73. $redis = CacheService::redisHandler($tag);
  74. return new Tag($redis, $tag);
  75. }
  76. /**
  77. * 总缓存数据量
  78. * @return mixed
  79. */
  80. public function cacheCount()
  81. {
  82. $cacheKey = $this->cacheKey();
  83. $rds = $this->getRedisConnect();
  84. return $rds->hLen($cacheKey . 'map');
  85. }
  86. /**
  87. * 读取缓存全部数据
  88. * @return mixed
  89. */
  90. public function cacheList(string $key = '')
  91. {
  92. $cacheKey = $this->cacheKey() . $key;
  93. $rds = $this->getRedisConnect();
  94. $map = $rds->hGetAll($cacheKey . 'map');
  95. //key排序
  96. ksort($map);
  97. $list = array_values($map) ?: [];
  98. foreach ($list as $key => $item) {
  99. $list[$key] = $this->unserialize($item);
  100. }
  101. return $list;
  102. }
  103. /**
  104. * 读取缓存分页数据
  105. * @param int $page
  106. * @param int $limit
  107. * @param string $key
  108. * @return array
  109. */
  110. public function cachePageData(int $page = 1, int $limit = 10, string $key = '')
  111. {
  112. $cacheKey = $this->cacheKey() . $key;
  113. $rds = $this->getRedisConnect();
  114. $page = max($page, 1);
  115. $limit = max($limit, 1);
  116. //先读排序
  117. $pageList = $rds->zRangeByScore($cacheKey . 'page', ($page - 1) * $limit, ($page * $limit) - 1);
  118. //再读数据
  119. $list = $rds->hMGet($cacheKey . 'map', $pageList) ?: [];
  120. if (is_array($list)) {
  121. $newList = [];
  122. foreach ($list as $value) {
  123. $newList[] = $this->unserialize($value);
  124. }
  125. $list = $newList;
  126. }
  127. $count = $rds->hLen($cacheKey . 'map');
  128. return compact('list', 'count');
  129. }
  130. /**
  131. * 单个查询数据
  132. * @param int|string $id
  133. * @return false|string|array
  134. */
  135. public function cacheInfoById($id)
  136. {
  137. $cacheKey = $this->cacheKey();
  138. $rds = $this->getRedisConnect();
  139. $value = $rds->hGet($cacheKey . 'map', $id);
  140. return $value === null ? null : $this->unserialize($value);
  141. }
  142. /**
  143. * 批量查询数据
  144. * @param $ids
  145. * @return mixed
  146. */
  147. public function cacheInfoByIds(array $ids)
  148. {
  149. $cacheKey = $this->cacheKey();
  150. $rds = $this->getRedisConnect();
  151. $arr = $rds->hMGet($cacheKey . 'map', $ids);
  152. if (is_array($arr)) {
  153. $newList = [];
  154. foreach ($arr as $key => $value) {
  155. $arr[$key] = $this->unserialize($value);
  156. }
  157. $arr = $newList;
  158. }
  159. return $arr;
  160. }
  161. /**
  162. * 更新单个缓存
  163. * @param $info
  164. * @return false|mixed
  165. */
  166. public function cacheUpdate(array $info, $key = null)
  167. {
  168. $pk = $this->getPk();
  169. if ((empty($info) || !isset($info[$pk])) && !$key) {
  170. return false;
  171. }
  172. $cacheKey = $this->cacheKey();
  173. $rds = $this->getRedisConnect();
  174. $key = $key ?: $info[$pk];
  175. return $rds->hSet($cacheKey . 'map', $key, $this->serialize($info));
  176. }
  177. /**
  178. * 序列化数据
  179. * @param $value
  180. * @return string
  181. * @author 等风来
  182. * @email 136327134@qq.com
  183. * @date 2022/11/10
  184. */
  185. private function serialize($value)
  186. {
  187. try {
  188. return serialize($value);
  189. } catch (\Throwable $e) {
  190. Log::error('序列化发生错误:' . $e->getMessage());
  191. return $value;
  192. }
  193. }
  194. /**
  195. * 反序列化数据
  196. * @param $value
  197. * @return mixed
  198. * @author 等风来
  199. * @email 136327134@qq.com
  200. * @date 2022/11/10
  201. */
  202. private function unserialize($value)
  203. {
  204. try {
  205. return unserialize($value);
  206. } catch (\Throwable $e) {
  207. Log::error('反序列化发生错误:' . $e->getMessage());
  208. return $value;
  209. }
  210. }
  211. /**
  212. * @param int $id
  213. * @param $field
  214. * @param null $value
  215. * @return false|mixed
  216. * @author 等风来
  217. * @email 136327134@qq.com
  218. * @date 2022/11/1
  219. */
  220. public function cacheSaveValue(int $id, $field, $value = null)
  221. {
  222. $pk = $this->getPk();
  223. $info = $this->cacheInfoById($id);
  224. if (!$info) {
  225. $newInfo = $this->get($id);
  226. $info = $newInfo ? $newInfo->toArray() : [];
  227. }
  228. if (is_array($field)) {
  229. foreach ($field as $k => $v) {
  230. $info[$k] = $v;
  231. }
  232. } else {
  233. $info[$field] = $value;
  234. }
  235. $info[$pk] = $id;
  236. return $this->cacheUpdate($info);
  237. }
  238. /**
  239. * 不存在则写入,存在则返回
  240. * @param $key
  241. * @param callable|null $fn
  242. * @param null $default
  243. * @return array|false|mixed|string|null
  244. * @author 等风来
  245. * @email 136327134@qq.com
  246. * @date 2022/11/1
  247. */
  248. public function cacheRemember($key, callable $fn = null, $default = null)
  249. {
  250. //不开启数据缓存直接返回
  251. if (!app()->config->get('cache.is_data')) {
  252. if ($fn instanceof \Closure) {
  253. return Container::getInstance()->invokeFunction($fn);
  254. } else {
  255. return $default;
  256. }
  257. }
  258. $info = $this->cacheInfoById($key);
  259. if ((null === $info || false === $info) && is_callable($fn)) {
  260. //读取数据库缓存
  261. $newInfo = $fn();
  262. if (null !== $newInfo) {
  263. //缓存数据存在则更新
  264. $this->cacheUpdate($newInfo, $key);
  265. }
  266. $info = $newInfo;
  267. }
  268. return null !== $info ? $info : $default;
  269. }
  270. /**
  271. * 批量更新缓存
  272. * @param $list
  273. * @return false|mixed
  274. */
  275. public function cacheUpdateList(array $list, string $key = '')
  276. {
  277. if (empty($list)) {
  278. return false;
  279. }
  280. $cacheKey = $this->cacheKey() . $key;
  281. $pk = $this->getPk();
  282. $rds = $this->getRedisConnect();
  283. $map = [];
  284. foreach ($list as $item) {
  285. if (empty($item) || !isset($item[$pk])) {
  286. continue;
  287. }
  288. $map[$item[$pk]] = $this->serialize($item);
  289. }
  290. return $rds->hMSet($cacheKey . 'map', $map);
  291. }
  292. /**
  293. * 删除单条缓存
  294. * @param $id
  295. */
  296. public function cacheDelById(int $id)
  297. {
  298. $cacheKey = $this->cacheKey();
  299. $rds = $this->getRedisConnect();
  300. $rds->hDel($cacheKey . 'map', $id);
  301. $rds->zRem($cacheKey . 'page', $id);
  302. }
  303. /**
  304. * 批量删除缓存
  305. * @param $ids
  306. */
  307. public function cacheDelByIds(array $ids)
  308. {
  309. $cacheKey = $this->cacheKey();
  310. $rds = $this->getRedisConnect();
  311. foreach ($ids as $id) {
  312. $rds->hDel($cacheKey . 'map', $id);
  313. $rds->zRem($cacheKey . 'page', $id);
  314. }
  315. }
  316. /**
  317. * 创建缓存
  318. * @param array $list
  319. * @author 等风来
  320. * @email 136327134@qq.com
  321. * @date 2022/10/29
  322. */
  323. public function cacheCreate(array $list, string $key = '')
  324. {
  325. $pk = $this->getPk();
  326. $cacheKey = $this->cacheKey() . $key;
  327. $rds = $this->getRedisConnect();
  328. //启动事务
  329. $rds->multi();
  330. //删除旧数据
  331. $rds->del($cacheKey . 'map');
  332. $rds->del($cacheKey . 'page');
  333. //组合数据
  334. $map = [];
  335. foreach ($list as $i => $item) {
  336. $map[$item[$pk]] = $item;
  337. //存zset 排序
  338. $rds->zAdd($cacheKey . 'page', $i, $item[$pk]);
  339. }
  340. foreach ($map as $k => &$item) {
  341. $item = $this->serialize($item);
  342. }
  343. //存hmset 数据
  344. $rds->hMSet($cacheKey . 'map', $map);
  345. //执行事务
  346. $rds->exec();
  347. }
  348. protected function cacheKey()
  349. {
  350. return 'mc:' . $this->getModel()->getName() . ':';
  351. }
  352. /**
  353. *
  354. * @param $key
  355. * @return string
  356. * @author 等风来
  357. * @email 136327134@qq.com
  358. * @date 2022/11/10
  359. */
  360. public function getCacheKey($key)
  361. {
  362. return $this->cacheKey() . $key;
  363. }
  364. /**
  365. * 更新缓存
  366. * @param string $key
  367. * @param $value
  368. * @return bool
  369. * @author 等风来
  370. * @email 136327134@qq.com
  371. * @date 2022/11/1
  372. */
  373. public function cacheStrUpdate(string $key, $value, int $expire = null)
  374. {
  375. return $this->getCacheHander()->set($this->cacheKey() . 'str:' . $key, $value, $expire);
  376. }
  377. /**
  378. * 获取缓存
  379. * @param string $key
  380. * @return false|mixed|string
  381. * @author 等风来
  382. * @email 136327134@qq.com
  383. * @date 2022/11/1
  384. */
  385. public function cacheStrGet(string $key)
  386. {
  387. return $this->getCacheHander()->get($this->cacheKey() . 'str:' . $key);
  388. }
  389. /**
  390. * 获取表缓存是否有数据
  391. * @return false|mixed|string
  392. * @author 等风来
  393. * @email 136327134@qq.com
  394. * @date 2022/11/1
  395. */
  396. public function cacheStrTable()
  397. {
  398. return $this->getRedisConnect()->get($this->cacheKey());
  399. }
  400. /**
  401. * 设置表缓存是否有数据
  402. * @param int $value
  403. * @return bool
  404. * @author 等风来
  405. * @email 136327134@qq.com
  406. * @date 2022/11/1
  407. */
  408. public function cacheStrSetTable(int $value = 1)
  409. {
  410. return $this->getRedisConnect()->set($this->cacheKey(), $value);
  411. }
  412. /**
  413. * 删除缓存
  414. * @param string $key
  415. * @return int
  416. * @author 等风来
  417. * @email 136327134@qq.com
  418. * @date 2022/11/1
  419. */
  420. public function cacheStrDel(string $key)
  421. {
  422. return $this->getCacheHander()->delete($this->cacheKey() . 'str:' . $key);
  423. }
  424. /**
  425. * 获取缓存,没有则写入缓存并返回
  426. * @param string $key
  427. * @param callable|null $fn
  428. * @param null $default
  429. * @return false|mixed|string|null
  430. * @author 等风来
  431. * @email 136327134@qq.com
  432. * @date 2022/11/1
  433. */
  434. public function cacheStrRemember(string $key, callable $fn = null, int $expire = null, $default = null)
  435. {
  436. //不开启数据缓存直接返回
  437. if (!app()->config->get('cache.is_data')) {
  438. if ($fn instanceof \Closure) {
  439. return Container::getInstance()->invokeFunction($fn);
  440. } else {
  441. return $default;
  442. }
  443. }
  444. $value = $this->cacheStrGet($key);
  445. if ((null === $value || false === $value) && is_callable($fn)) {
  446. $newValue = $fn();
  447. if (null !== $newValue) {
  448. $this->cacheStrUpdate($key, $value, $expire);
  449. }
  450. $value = $newValue;
  451. }
  452. return null !== $value ? $value : $default;
  453. }
  454. }