Home >PHP Framework >ThinkPHP >About the implementation of multiple Redis classes in ThinkPHP6
The following tutorial column will introduce you to multiple Redis class implementations in ThinkPHP6. I hope it will be helpful to friends in need!
1. Preparation before operationIf the phpredis module is not installed, execute it first
composer require predis/predis2. Configure Redis connection information Configure in app\config\cache.php
'redis' => [ // 驱动方式 'type' => 'redis', // 连接地址 'host' => Env::get('redis.host'), // 端口 'port' => Env::get('redis.port'),],More configuration reference
/** * 配置参数 * @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' => [],];Configure connection information in .env
[REDIS]host = 127.0.0.1 port = 6379
3. Write code
Create the file Redis.php under app\common<?phpnamespace 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. How to use
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');For more usage methods, please refer to
redis command manual
The above is the detailed content of About the implementation of multiple Redis classes in ThinkPHP6. For more information, please follow other related articles on the PHP Chinese website!