PHP中Redis分布式

2017-09-21 19:55  768人阅读  评论 (0)
Tags: redis

RedisCluster.php

<?php
class RedisCluster {
    public $servers = array();

    public function addServer($host, $port) {
        $redis = new Redis();
        $redis->_connected = false;
        $redis->_host = $host;
        $redis->_port = $port;
        $this->servers[] = $redis;
    }

    public function __call($method, $args) {
        if (!method_exists("Redis", $method)) {
            throw new Execption("not method");
        }
        $redis = $this->servers[abs(crc32($args[0])) % count($this->servers)];
        if (!$redis->_connected) {
            $redis->connect($redis->_host, $redis->_port);
            $redis->_connected = true;
        }
        // return $redis->$method(...$args); // PHP 5.6
        return call_user_func_array([$redis, $method], $args);
    }
}

$rc = new RedisCluster();
$rc->addServer("127.0.0.1", 8000);
$rc->addServer("127.0.0.1", 8001);

$rc->set("a", 1);
$rc->set("b", 2);
$rc->set("c", 3);
$rc->set("d", 4);
$rc->set("e", 5);