关于ThinkPHP6多例Redis类实现
5390
在Thinkphp项目中封装一个Redis多库单例操作类
1、操作前的准备
如果没有安装phpredis模块那么先执行
- composer require predis/predis
2、配置Redis连接信息
在app\config\cache.php中配置
- 'redis' => [
- // 驱动方式
- 'type' => 'redis',
- // 连接地址
- 'host' => Env::get('redis.host'),
- // 端口
- 'port' => Env::get('redis.port'),
- ],
更多配置参考
- /**
- * 配置参数
- * @var array
- */
- protected $options = [
- 'host' => '127.0.0.1',
- 'port' => 6379,
- 'password' => '',
- 'select' => 0,
- 'timeout' => 0,
- 'expire' => 0,
- 'persistent' => false,
- 'prefix' => '',
- 'tag_prefix' => 'tag:',
- 'serialize' => [],
- ];
在.env中配置连接信息
- [REDIS]host = 127.0.0.1
- port = 6379
3、编写代码
在app\common下创建文件Redis.php
- <?php
- namespace app\common;
- use think\facade\Config;
- use think\cache\driver\redis as ThinkRedis;
- class Redis extends ThinkRedis
- {
- /**
- * @var int
- */
- protected $hash;
- /**
- * @var array
- */
- protected static $instance = [];
- /**
- * Redis constructor.
- * @param $db
- */
- private function __construct($db)
- {
- $options = Config::get('cache.stores.redis');
- $options['select'] = $db;
- $this->hash = $db;
- $this->options = array_merge($this->options, $options);
- parent::__construct();
- }
- private function __clone()
- {
- }
- /**
- * @param int $db
- * @return \Predis\Client|\Redis
- */
- public static function instance($db = 0)
- {
- if (! isset(self::$instance[$db])) {
- self::$instance[$db] = new self($db);
- }
- return self::$instance[$db];
- }
- public function __destruct()
- {
- self::$instance[$this->hash]->close();
- unset(self::$instance[$this->hash]);
- }
- }
4、使用方式
- use app\common\Redis;
- $redis = Redis::instance(4);
- $redis->hSet('user:1', 'userName', 'admin');
- Redis::instance(1)->hSet('user', 'name', 'admin1');
- Redis::instance(2)->hSet('user', 'name', 'admin2');
- Redis::instance(3)->hSet('user', 'name', 'admin3');
本文网址:https://www.zztuku.com/detail-7930.html
站长图库 - 关于ThinkPHP6多例Redis类实现
申明:如有侵犯,请 联系我们 删除。
您还没有登录,请 登录 后发表评论!
提示:请勿发布广告垃圾评论,否则封号处理!!