CacheTrait.php 996 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. namespace App\Base\Services;
  3. use Predis\Client;
  4. trait CacheTrait
  5. {
  6. protected function getCacheClient()
  7. {
  8. return new Client(config('database.redis.default'));
  9. }
  10. /**
  11. * 缓存前缀
  12. * @return string
  13. */
  14. protected function getPrefix()
  15. {
  16. return config('cache.prefix') ? (config('cache.prefix') . ':') : '';
  17. }
  18. /**
  19. * 获取所有前缀为$key的所有key
  20. * @param $key
  21. * @return array
  22. */
  23. public function getCacheKeys($key)
  24. {
  25. return $this->getCacheClient()->keys($this->getPrefix() . $key . '*');
  26. }
  27. public function getCacheKeysAll($key)
  28. {
  29. return $this->getCacheClient()->keys('*' . $key . '*');
  30. }
  31. /**
  32. * 模糊清除所有前缀的缓存
  33. * @param $key
  34. */
  35. public function removeByKey($key)
  36. {
  37. $list = $this->getCacheKeysAll($key);
  38. foreach ($list as $item) {
  39. $this->getCacheClient()->del($item);
  40. }
  41. }
  42. }