>  기사  >  PHP 프레임워크  >  ThinkPHP6의 여러 Redis 클래스 구현 정보

ThinkPHP6의 여러 Redis 클래스 구현 정보

藏色散人
藏色散人앞으로
2020-09-08 09:50:365587검색

다음 튜토리얼 칼럼인 thinkphp에서는 ThinkPHP6의 Redis 클래스 구현에 대한 여러 예제를 소개하겠습니다. 도움이 필요한 친구들에게 도움이 되길 바랍니다!

ThinkPHP6의 여러 Redis 클래스 구현 정보

Thinkphp 프로젝트에서 Redis 다중 라이브러리 싱글톤 작업 클래스를 캡슐화합니다

1 작업 전 준비

phpredis 모듈이 설치되지 않은 경우 실행합니다. 그것 먼저

composer require predis/predis

2. Redis 연결 정보 구성

appconfigcache.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

에서 연결 정보 구성

appcommon 아래에 파일을 생성합니다. Redis.php

<?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(&#39;cache.stores.redis&#39;);
        $options[&#39;select&#39;] = $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(&#39;user:1&#39;, &#39;userName&#39;, &#39;admin&#39;);

Redis::instance(1)->hSet(&#39;user&#39;, &#39;name&#39;, &#39;admin1&#39;);
Redis::instance(2)->hSet(&#39;user&#39;, &#39;name&#39;, &#39;admin2&#39;);
Redis::instance(3)->hSet(&#39;user&#39;, &#39;name&#39;, &#39;admin3&#39;);

자세한 사용방법은 redis 명령어 매뉴얼

을 참고하세요.

위 내용은 ThinkPHP6의 여러 Redis 클래스 구현 정보의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 csdn.net에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제