>  기사  >  백엔드 개발  >  laravel5.2 및 redis_cluster 구성 소개

laravel5.2 및 redis_cluster 구성 소개

巴扎黑
巴扎黑원래의
2017-08-17 08:57:541924검색


요약: laravel에서 redis 클러스터를 적용하는 부분에서는 laravel5.2의 redis 클러스터 구성을 공유하고 싶습니다. (공식 웹사이트에도 redis 클러스터 구성에 대한 설명이 있지만, 버전 5.2는 아직 조금 부족해서 클러스터 구성에 대해서만 이야기하고 있습니다. 항목이 true로 설정되어 있지만 이러한 옵션만으로는 초보자가 redis 세트를 직접 사용할 수 있다는 의미는 아닙니다...

redis 클러스터 적용 laravel

이번 편에서는 laravel5.2의 redis 클러스터 구성에 대해 공유해볼까 합니다. ( 공식 홈페이지에도 redis 클러스터 구성에 대한 설명이 있지만 5.2 버전은 아직 좀 부족합니다. 클러스터 구성 항목을 true로 설정하지만 이 옵션만으로는 초보자가 redis 클러스터를 직접 사용할 수는 없습니다. 이 부분에는 predis 클라이언트도 포함되어 있으므로 나중에 predis의 소스 코드 분석도 공유하겠습니다.)

redis- 클러스터 구성: Easy Building Redis-cluster (쉽게 reids 클러스터 구축)

시스템 소프트웨어 목록:

  • laravel 버전: 5.2

  • redis 버전:>=3.0 최신 버전을 다운로드하세요

  • predis:>=1.0 다운로드 주소

구성 파일: config/database.php

'redis' => [    'cluster' => env('REDIS_CLUSTER', true),
    **'options'=>['cluster'=>'redis']**,  //官网没说这个,这是必须的!!后面会讲为什么这么配?
    'default' => [        'host' => env('REDIS_HOST', '127.0.0.1'), //任选一个master节点
        'port' => env('REDIS_PORT',6379),        'database' => 0,        'timeout'=>15,        'read_write_timeout'=>1800 //redis客户端连接以后的读写超时时间(默认是60s)
    ],    'extra'=>[                      
        'host'=>env('REDIS_EXTRA_HOST','127.0.0.1'),  //任意一个集群中的节点即可
        'port'=>env('REDIS_EXTRA_PORT',7001)
    ]
 ]

위의 단계를 완료한 후 redis 클러스터를 사용할 수 있습니다.
비즈니스 요구에 따라 Redis 클러스터를 사용하기 위한 다양한 특정 애플리케이션 시나리오가 있습니다. 클러스터링으로 세션 등을 저장합니다.
app('request')->session()->put('key','value');

predis의 기본 구현 redis Cluster

좋아요, 구성 파일의 매개변수를 이해하려면 소스 코드와 물론 predis도 살펴봐야 합니다.

Illuminate\Support\ServiceProvider\RedisServiceProvider;    public function register()
    {        $this->app->singleton('redis', function ($app) {            return new Database($app['config']['database.redis']);
        });
    }
 

 Illuminate\Redis\Database;    
     public function __construct(array $servers = [])
     {
        $cluster = Arr::pull($servers, 'cluster');   //获取'cluster'的键值
       
        $options = (array) Arr::pull($servers, 'options');       //options 就是database.php中'options'的键值,是一个数组(但官网没有提到,是个坑.)
        if ($cluster) {  
            $this->clients = $this->createAggregateClient($servers, $options);   //集群模式'cluster=true'
        } else {       
             $this->clients = $this->createSingleClients($servers, $options);   //单机模式 'cluster=false'
        }
    }   protected function createAggregateClient(array $servers, array $options = [])
    {                
        return ['default' => new Client(array_values($servers), $options)];   //predis的Client类
    }
    


----------


注意:这里提醒一下各参数的值:
此时$servers=[
    [      'host' => env('REDIS_HOST', '127.0.0.1'),      'port' => env('REDIS_PORT',6379),      'database' => 0,      'timeout'=>15,      'read_write_timeout'=>1800
    ],
    [      'host'=>env('REDIS_EXTRA_HOST','127.0.0.1'),      'port'=>env('REDIS_EXTRA_PORT',7001)
    ]
]
$options = ['cluster'=>'redis']

其实到这儿,就可以解释在database.php中增加options选项,而且是必选项,因为底层代码需要判断数据切片的方式.
除了看源码,
predis的包文档也做了解释.https://packagist.org/packages/predis/predis-------

다음으로 이러한 기본 클래스를 살펴보겠습니다. 초기화됩니다.

  Predis\Client;      public function __construct($parameters = null, $options = null)
    {        $this->options = $this->createOptions($options ?: array());        #$this->connection = $this->createConnection($parameters ?: array());
        #$this->profile = $this->options->profile;
    }    
    protected function createOptions($options)
    {        if (is_array($options)) {            return new Options($options);  //如你所见,实例化Options类
        }        if ($options instanceof OptionsInterface) {            return $options;
        }        throw new \InvalidArgumentException('Invalid type for client options.');
    }   
    public function __construct(array $options = array())
    {        $this->input = $options;        $this->options = array();        $this->handlers = $this->getHandlers();
    }

$this-> 연결 = $this->createConnection($parameters?: array())

Predis\Client 文件

    protected function createConnection($parameters)
    {
       # if ($parameters instanceof ConnectionInterface) {
       #     return $parameters;
       # }

       # if ($parameters instanceof ParametersInterface || is_string($parameters)) {
       #     return $this->options->connections->create($parameters);
       # }

       # if (is_array($parameters)) {
       #     if (!isset($parameters[0])) {
       #         return $this->options->connections->create($parameters);
       #     }            $options = $this->options;

       #     if ($options->defined('aggregate')) {
       #         $initializer = $this->getConnectionInitializerWrapper($options->aggregate);
       #         $connection = $initializer($parameters, $options);
       #     } else {
       #         if ($options->defined('replication') && $replication = $options->replication) {
       #             $connection = $replication;
       #         } else {                
                    $connection = $options->cluster; //
       #         }                $options->connections->aggregate($connection, $parameters);
       #     }

            return $connection;
       # }

       # if (is_callable($parameters)) {
       #     $initializer = $this->getConnectionInitializerWrapper($parameters);
       #     $connection = $initializer($this->options);

       #     return $connection;
       # }

       # throw new \InvalidArgumentException('Invalid type for connection parameters.');
    }
    
Predis\Configuration\Options;

    protected function getHandlers()
    {
        return array(            'cluster' => 'Predis\Configuration\ClusterOption',            'connections' => 'Predis\Configuration\ConnectionFactoryOption',
            #'exceptions' => 'Predis\Configuration\ExceptionsOption',
            #'prefix' => 'Predis\Configuration\PrefixOption',
            #'profile' => 'Predis\Configuration\ProfileOption',
            #'replication' => 'Predis\Configuration\ReplicationOption',
        );
    }

    public function __get($option)
    {
        #if (isset($this->options[$option]) || array_key_exists($option, $this->options)) {
        #    return $this->options[$option];
        #}         if (isset($this->input[$option]) || array_key_exists($option, $this->input)) {            $value = $this->input[$option];
            unset($this->input[$option]);

        #    if (is_object($value) && method_exists($value, '__invoke'){
        #        $value = $value($this, $option);
        #    }            if (isset($this->handlers[$option])) {                $handler = $this->handlers[$option];                $handler = new $handler(); //会实例化Predis\Configuration\ClusterOption类
                $value = $handler->filter($this, $value);
            }

            return $this->options[$option] = $value;
        }

       # if (isset($this->handlers[$option])) {
       #     return $this->options[$option] = $this->getDefault($option);
       # }

       # return;
    }
    
Predis\Configuration\ClusterOption文件

    public function filter(OptionsInterface $options, $value)
    {        if (is_string($value)) {            $value = $this->createByDescription($options, $value);
        }

       # if (!$value instanceof ClusterInterface) {
       #     throw new \InvalidArgumentException(
       #         "An instance of type 'Predis\Connection\Aggregate\ClusterInterface' was expected."
       #     );
       # }

        return $value;
    }
       
       
        protected function createByDescription(OptionsInterface $options, $id)
    {
        switch ($id) {
         * Abstraction for a cluster of aggregate connections to various Redis servers
 * implementing client-side sharding based on pluggable distribution strategies.
          # case 'predis':
          # case 'predis-cluster':
          #      return new PredisCluster(); 
          //这个模式是客户端通过CRC16算法在客户端进行数据切片,
          显然这种模式的集群是脆弱的,如果一个master节点挂了,
          那其备节点若也挂了,那么获取数据就成问题了;
          再有这种模式扩展性很差,维护成本高,
          因此这个模式不推荐.当然用最新predis不存在这个问题.
          我这边predis,1.0算比较老了.

            case 'redis':
            case 'redis-cluster':
                return new RedisCluster($options->connections);            //这种模式是基于服务端的数据切片,相较于第一种模式,优点也显而易见,维护成本低,扩展性好等.
            default:
                return;
        }
    } 
    
        public function __get($option)
    {
        #if (isset($this->options[$option]) || array_key_exists($option, $this->options)) {
        #    return $this->options[$option];
        #}

        # if (isset($this->input[$option]) || array_key_exists($option, $this->input)) {
        #    $value = $this->input[$option];
        #    unset($this->input[$option]);

        #    if (is_object($value) && method_exists($value, '__invoke'){
        #        $value = $value($this, $option);
        #    }

        #    if (isset($this->handlers[$option])) {
        #       $handler = $this->handlers[$option];
        #        $handler = new $handler(); 
        #        $value = $handler->filter($this, $value);
        #    }

        #    return $this->options[$option] = $value;
        #}         if (isset($this->handlers[$option])) {  //$options='connections'       
            return $this->options[$option] = $this->getDefault($option);
       # }

       # return;
    }  
    
    public function getDefault($option)
    {        if (isset($this->handlers[$option])) {            $handler = $this->handlers[$option]; //$handler = 'Predis\Configuration\ConnectionFactoryOption';
            $handler = new $handler();

            return $handler->getDefault($this);
        }
    }
    
 Predis\Configuration\ConnectionFactoryOption文件
    public function getDefault(OptionsInterface $options)
    {
        return new Factory(); //最后实例化了一个'工厂'类
    }

$this->profile = $this->options->profile;


Predis\Configuration\ProfileOption文件


        public function __get($option)
    {
        #if (isset($this->options[$option]) || array_key_exists($option, $this->options)) {
        #    return $this->options[$option];
        #}

        # if (isset($this->input[$option]) || array_key_exists($option, $this->input)) {
        #    $value = $this->input[$option];
        #    unset($this->input[$option]);

        #    if (is_object($value) && method_exists($value, '__invoke'){
        #        $value = $value($this, $option);
        #    }

        #    if (isset($this->handlers[$option])) {
        #       $handler = $this->handlers[$option];
        #        $handler = new $handler(); 
        #        $value = $handler->filter($this, $value);
        #    }

        #    return $this->options[$option] = $value;
        #}         if (isset($this->handlers[$option])) {  //$options='profile'       
            return $this->options[$option] = $this->getDefault($option);
       # }

       # return;
    }  
    
        public function getDefault($option)
    {        if (isset($this->handlers[$option])) {            $handler = $this->handlers[$option]; //$handler = 'Predis\Configuration\ProfileOption';
            $handler = new $handler();

            return $handler->getDefault($this);
        }
    }
    
 Predis\Configuration\ProfileOption文件
     public function getDefault(OptionsInterface $options)
    {        $profile = Factory::getDefault(); //实例化了Predis\Profile\RedisVersion300类
        $this->setProcessors($options, $profile);

        return $profile;  
    }

위 내용은 laravel5.2 및 redis_cluster 구성 소개의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.