关于ThinkPHP6多例Redis类实现

 5390

关于ThinkPHP6多例Redis类实现


在Thinkphp项目中封装一个Redis多库单例操作类

1、操作前的准备

如果没有安装phpredis模块那么先执行

  1. composer require predis/predis

2、配置Redis连接信息

在app\config\cache.php中配置

  1. 'redis' => [
  2.     // 驱动方式
  3.     'type'       => 'redis',
  4.     // 连接地址
  5.     'host'       => Env::get('redis.host'),
  6.     // 端口
  7.     'port'       => Env::get('redis.port'),
  8. ],

更多配置参考

  1. /**
  2.  * 配置参数
  3.  * @var array
  4.  */
  5. protected $options = [
  6.     'host'       => '127.0.0.1',
  7.     'port'       => 6379,
  8.     'password'   => '',
  9.     'select'     => 0,
  10.     'timeout'    => 0,
  11.     'expire'     => 0,
  12.     'persistent' => false,
  13.     'prefix'     => '',
  14.     'tag_prefix' => 'tag:',
  15.     'serialize'  => [],
  16. ];

在.env中配置连接信息

  1. [REDIS]host = 127.0.0.1
  2. port = 6379

3、编写代码

在app\common下创建文件Redis.php

  1. <?php
  2. namespace app\common;
  3. use think\facade\Config;
  4. use think\cache\driver\redis as ThinkRedis;
  5. class Redis extends ThinkRedis
  6. {
  7.     /**
  8.      * @var int
  9.      */
  10.     protected $hash; 
  11.     /**
  12.      * @var array
  13.      */
  14.     protected static $instance = []; 
  15.     /**
  16.      * Redis constructor.
  17.      * @param $db
  18.      */
  19.     private function __construct($db)
  20.     {
  21.         $options = Config::get('cache.stores.redis');
  22.         $options['select'] = $db;
  23.         $this->hash = $db;
  24.         $this->options = array_merge($this->options, $options);
  25.         parent::__construct();
  26.     } 
  27.     private function __clone()
  28.     {
  29.     } 
  30.     /**
  31.      * @param int $db
  32.      * @return \Predis\Client|\Redis
  33.      */
  34.     public static function instance($db = 0)
  35.     {
  36.         if (! isset(self::$instance[$db])) {
  37.             self::$instance[$db] = new self($db);
  38.         }
  39.         return self::$instance[$db];
  40.     } 
  41.     public function __destruct()
  42.     {
  43.         self::$instance[$this->hash]->close();
  44.         unset(self::$instance[$this->hash]);
  45.     }
  46. }

4、使用方式

  1. use app\common\Redis;
  2. $redis = Redis::instance(4);
  3. $redis->hSet('user:1', 'userName', 'admin'); 
  4. Redis::instance(1)->hSet('user', 'name', 'admin1');
  5. Redis::instance(2)->hSet('user', 'name', 'admin2');
  6. Redis::instance(3)->hSet('user', 'name', 'admin3');



本文网址:https://www.zztuku.com/detail-7930.html
站长图库 - 关于ThinkPHP6多例Redis类实现
申明:如有侵犯,请 联系我们 删除。

评论(0)条

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

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

    编辑推荐

    黄金钱币集合矢量素材