CacheService.php 2.4 KB

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