123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192 |
- <?php
- namespace crmeb\services;
- use think\facade\Cache;
- use think\facade\Config;
- use think\cache\TagSet;
- class CacheService
- {
-
- protected static $expire;
-
- public static function set(string $name, $value, int $expire = 0, string $tag = 'crmeb')
- {
- try {
- return Cache::tag($tag)->set($name, $value, $expire);
- } catch (\Throwable $e) {
- return false;
- }
- }
-
- public static function remember(string $name, $default = '', int $expire = 0, string $tag = 'crmeb')
- {
- try {
- return Cache::tag($tag)->remember($name, $default, $expire);
- } catch (\Throwable $e) {
- try {
- if (is_callable($default)) {
- return $default();
- } else {
- return $default;
- }
- } catch (\Throwable $e) {
- return null;
- }
- }
- }
-
- public static function get(string $name, $default = '')
- {
- return Cache::get($name) ?? $default;
- }
-
- public static function delete(string $name)
- {
- return Cache::delete($name);
- }
-
- public static function clear(string $tag = 'crmeb')
- {
- return Cache::tag($tag)->clear();
- }
-
- public static function clearAll()
- {
- return Cache::clear();
- }
-
- public static function has(string $key)
- {
- try {
- return Cache::has($key);
- } catch (\Throwable $e) {
- return false;
- }
- }
-
- public static function store(string $type = 'file', string $tag = 'crmeb')
- {
- return Cache::store($type)->tag($tag);
- }
-
- public static function setMutex(string $key, int $timeout = 10): bool
- {
- $curTime = time();
- $readMutexKey = "redis:mutex:{$key}";
- $mutexRes = Cache::store('redis')->handler()->setnx($readMutexKey, $curTime + $timeout);
- if ($mutexRes) {
- return true;
- }
-
- $time = Cache::store('redis')->handler()->get($readMutexKey);
- if ($curTime > $time) {
- Cache::store('redis')->handler()->del($readMutexKey);
- return Cache::store('redis')->handler()->setnx($readMutexKey, $curTime + $timeout);
- }
- return false;
- }
-
- public static function delMutex(string $key)
- {
- $readMutexKey = "redis:mutex:{$key}";
- Cache::store('redis')->handler()->del($readMutexKey);
- }
-
- public static function lock($key, $fn, int $ex = 6)
- {
- if (Config::get('cache.default') == 'file') {
- return $fn();
- }
- return app()->make(LockService::class)->exec($key, $fn, $ex);
- }
- }
|