分享TP6框架中Redis操作服务类的记录

 4306

下面给大家分享ThinkPHP6中Redis操作服务类的记录,希望对需要的朋友有所帮助!


1. 定义服务类

  1. <?php
  2.  
  3. declare (strict_types=1);
  4.  
  5. namespace app\api\service\common;
  6.  
  7. use think\facade\Cache;
  8.  
  9. /**
  10.  * 缓存服务
  11.  * Class RedisService
  12.  *
  13.  * @package app\api\service\common
  14.  */
  15. class RedisService
  16. {
  17.     private $expire;
  18.     private $expire_at;
  19.  
  20.     /**
  21.      * 获取redis句柄
  22.      *
  23.      * @return object|null
  24.      */
  25.     public function client(): ?object
  26.     {
  27.         return Cache::store('redis')->handler();
  28.     }
  29.  
  30.     /**
  31.      * 处理缓存key(添加前缀...)
  32.      *
  33.      * @param string $key  key
  34.      *
  35.      * @return string
  36.      */
  37.     private function cacheKey(string $key): string
  38.     {
  39.         return Cache::getCacheKey($key);
  40.     }
  41.  
  42.     /**
  43.      * 缓存程序运行结果
  44.      *
  45.      * @param          $key
  46.      * @param callable $callback
  47.      * @param int      $expire
  48.      *
  49.      * @return mixed
  50.      */
  51.     public function cache($key, callable $callback, int $expire = 3600)
  52.     {
  53.         $cache = $this->client()->get($key);
  54.         if (! $cache || ! unserialize($cache)) {
  55.             $data = $callback();
  56.             $this->client()->set($key, $cache = serialize($data), $expire);
  57.         }
  58.  
  59.         return unserialize($cache);
  60.     }
  61.  
  62.     /**
  63.      * 程序运行锁
  64.      * @param          $key
  65.      * @param callable $callback
  66.      * @param int      $timeout
  67.      *
  68.      * @return array
  69.      */
  70.     public function lock($key, callable $callback, int $timeout = 10): array
  71.     {
  72.         $lock = $this->client()->get($key);
  73.         if ($lock) return ['code' => 0, 'data' => null];
  74.         $this->client()->setex($key, $timeout, 1);
  75.         $data = $callback();
  76.         $this->client()->del($key);
  77.  
  78.         return ['code' => 1, 'data' => $data];
  79.     }
  80.  
  81.     /**
  82.      * 设置有效时间
  83.      *
  84.      * @param $ttl
  85.      *
  86.      * @return $this|false
  87.      * @throws \Exception
  88.      */
  89.     public function setExpire($ttl)
  90.     {
  91.         if ($this->expire_at) throw new \Exception('setExpire and setExpireAt can not set both');
  92.         $this->expire = $ttl;
  93.  
  94.         return $this;
  95.     }
  96.  
  97.     /**
  98.      * 设置到期时间
  99.      *
  100.      * @param $timestamp
  101.      *
  102.      * @return $this|false
  103.      * @throws \Exception
  104.      */
  105.     public function setExpireAt($timestamp)
  106.     {
  107.         if ($this->expire > 0) throw new \Exception('setExpire and setExpireAt can not set both');
  108.         $this->expire_at = $timestamp;
  109.  
  110.         return $this;
  111.     }
  112.  
  113.     /**
  114.      * 调用原生redis方法
  115.      *
  116.      * @return mixed
  117.      */
  118.     public function __call($name, $arguments)
  119.     {
  120.         $cache_key = $this->cacheKey($arguments[0]);
  121.  
  122.         $result = $this->client()->{$name}(...$arguments);
  123.  
  124.         // 设置过期时间
  125.         $this->expire && $this->client()->expire($cache_key, $this->expire);
  126.         $this->expire_at && $this->client()->expireAt($cache_key, $this->expire_at);
  127.  
  128.         return $result;
  129.     }
  130. }


2. 定义门面Facade

  1. <?php
  2.  
  3.  
  4. namespace app\api\facade;
  5.  
  6.  
  7. use app\api\service\common\RedisService;
  8. use think\Facade;
  9.  
  10. /**
  11.  * Class Redis
  12.  *
  13.  * @package app\api\facade
  14.  *
  15.  * @method static \Redis client()
  16.  * @method static \Redis setExpire($ttl)
  17.  * @method static \Redis setExpireAt($timestamp)
  18.  * @method static mixed cache($key, callable $callback, int $expire = 3600)
  19.  * @method static array lock($key, callable $callback, int $timeout = 10)
  20.  */
  21. class Redis extends Facade
  22. {
  23.     protected static function getFacadeClass()
  24.     {
  25.         return RedisService::class;
  26.     }
  27. }


3. 如何使用

3.1 程序锁

  1. public function test()
  2.     {
  3.         $a = 1;
  4.         $b = 2;
  5.         $result = Redis::lock('lock:demo', function () use ($a, $b) {
  6.             return $a + $b;
  7.         }, 5);
  8.         if ($result['code'] == 0) return '操作频繁,请稍后再试';
  9.         return $result['data']; // 成功返回数据 3
  10.     }

3.2 方法数据缓存

  1. public function test()
  2. {
  3.     $a = 1;
  4.     $b = 2;
  5.     $result = Redis::cache('cache:demo', function () use ($a, $b) {
  6.         return $a + $b;
  7.     }, 5);
  8.  
  9.     return $result; // 成功返回数据 3,有效时长5秒
  10. }

3.3 简化过期时间设置

  1. // 24小时到期
  2. Redis::setExpire(86400)->hSet('expire:demo', 'hash-key', 'hash-value');
  3. // 2021-08-24 23:59:59到期
  4. Redis::setExpireAt(strtotime('2021-08-24 23:59:59'))->hSet('expireAt:demo', 'hash-key', 'hash-value');

3.4 普通调用

  1. // 普通调用,直接跟redis方法名
  2. Redis::set('set:demo', 132456);
  3. // idea支持代码提示调用
  4. Redis::client()->set('set:demo', 132456);


本文网址:https://www.zztuku.com/detail-9085.html
站长图库 - 分享TP6框架中Redis操作服务类的记录
申明:如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐