CacheService.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. *
  4. * @author: xaboy<365615158@qq.com>
  5. * @day: 2018/01/05
  6. */
  7. namespace crmeb\services;
  8. use think\facade\Cache as CacheStatic;
  9. /**
  10. * crmeb 缓存类
  11. * Class CacheService
  12. * @package crmeb\services
  13. */
  14. class CacheService
  15. {
  16. /**
  17. * 标签名
  18. * @var string
  19. */
  20. protected static $globalCacheName = '_cached_1515146130';
  21. /**
  22. * 写入缓存
  23. * @param string $name 缓存名称
  24. * @param mixed $value 缓存值
  25. * @param int $expire 缓存时间,为0读取系统缓存时间
  26. * @return bool
  27. */
  28. public static function set(string $name, $value, int $expire = null): bool
  29. {
  30. //这里不要去读取缓存配置,会导致死循环
  31. $expire = !is_null($expire) ? $expire : SystemConfigService::get('cache_config', null, true);
  32. if (!is_int($expire))
  33. $expire = (int)$expire;
  34. return self::handler()->set($name, $value, $expire);
  35. }
  36. /**
  37. * 如果不存在则写入缓存
  38. * @param string $name
  39. * @param bool $default
  40. * @return mixed
  41. */
  42. public static function get(string $name, $default = false, int $expire = null)
  43. {
  44. //这里不要去读取缓存配置,会导致死循环
  45. $expire = !is_null($expire) ? $expire : SystemConfigService::get('cache_config', null, true);
  46. if (!is_int($expire))
  47. $expire = (int)$expire;
  48. return self::handler()->remember($name, $default, $expire);
  49. }
  50. /**
  51. * 删除缓存
  52. * @param string $name
  53. * @return bool
  54. * @throws \Psr\SimpleCache\InvalidArgumentException
  55. */
  56. public static function delete(string $name)
  57. {
  58. return CacheStatic::delete($name);
  59. }
  60. /**
  61. * 缓存句柄
  62. *
  63. * @return \think\cache\TagSet|CacheStatic
  64. */
  65. public static function handler()
  66. {
  67. return CacheStatic::tag(self::$globalCacheName);
  68. }
  69. /**
  70. * 清空缓存池
  71. * @return bool
  72. */
  73. public static function clear()
  74. {
  75. return self::handler()->clear();
  76. }
  77. }