CacheTrait.php 865 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. namespace App\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. /**
  28. * 模糊清除所有前缀的缓存
  29. * @param $key
  30. */
  31. public function removeByKey($key)
  32. {
  33. $list = $this->getCacheKeys($key);
  34. foreach($list as $item){
  35. $this->getCacheClient()->del($item);
  36. }
  37. }
  38. }