php封装redis负载均衡类

时间:2024-06-03 12:34:44
 $array = array(
'master' => array(
"redis://127.0.0.1:6379?timeout=1",
),
'slave' => array(
"redis://127.0.0.1:6479?timeout=1",
"redis://127.0.0.1:6579?timeout=1",
)
); $redis = RedisServer::instance($array);
$redis->set("aaaa","aaaa") //将会把数据缓存到.127.0.0.1:6379中
$redis->get("aaaa")//将会用127.0.0.1:6479或者127.0.0.1:6579中读取.从而实现读写分离
 <?php

 /**
* redis负载均衡
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* $array = array(
* 'master' => array(
* "redis://127.0.0.1:6379?timeout=1",
* ),
* 'slave' => array(
* "redis://127.0.0.1:6479?timeout=1",
* "redis://127.0.0.1:6579?timeout=1",
* )
* );
*
* $redis = RedisServer::instance($array);
* $redis->set("aaaa","aaaa") //将会把数据缓存到.127.0.0.1:6379中
* $redis->get("aaaa")//将会用127.0.0.1:6479或者127.0.0.1:6579中读取.从而实现读写分离
*
*
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* 如果本类报找不到方法.但是redis中存在改方法.请在列成员$methodMap中加入对应的方法.如果是缓存数据.设置为true,读取数据.设置为false
*
*
*
* Class RedisServer
* @author 136045277#qq.com
*/
class RedisServer
{
private static $masterServers = array();
private static $slaveServers = array(); private static $masterLength = 0;
private static $slaveLength = 0; private static $serverConfigs = array();
private static $dbIndex = null;
private static $instance = null; private static $prohibitMap = array(
'slaveof', 'config'
); private static $methodMap = array (
'del' => true,
'set' => true,
'get' => false,
'ttl' => false,
'hget' => false,
'incr' => true,
'lpop' => true,
'rpop' => true,
'spop' => true,
'decr' => true,
'ping' => true,
'info' => false,
'type' => false,
'hlen' => false,
'sadd' => true,
'keys' => false,
'mset' => true,
'exec' => true,
'hdel' => true,
'auth' => true,
'srem' => true,
'hset' => true,
'zrem' => true,
'scan' => false,
'dump' => false,
'zset' => true,
'move' => true,
'save' => true,
'lrem' => true,
'lset' => true,
'lget' => false,
'sort' => false,
'hmget' => false,
'ltrim' => true,
'hvals' => false,
'hkeys' => false,
'brpop' => true,
'lpush' => true,
'rpush' => true,
'smove' => true,
'setex' => true,
'watch' => true,
'multi' => true,
'bitop' => true,
'setnx' => true,
'zrank' => false,
'sscan' => false,
'hscan' => false,
'scard' => false,
'hmset' => true,
'zsize' => false,
'ssize' => false,
'lsize' => false,
'zscan' => false,
'blpop' => true,
'sdiff' => false,
'zcard' => false,
'exists' => false,
'zrange' => false,
'lindex' => false,
'getbit' => false,
'sunion' => false,
'sinter' => false,
'strlen' => false,
'decrby' => true,
'object' => false,
'incrby' => true,
'zinter' => true,
'getset' => true,
'lrange' => true,
'append' => true,
'lpushx' => true,
'zscore' => false,
'dbsize' => false,
'zcount' => false,
'zunion' => true,
'expire' => true,
'config' => true,
'rename' => true,
'setbit' => true,
'delete' => true,
'zincrby' => true,
'lremove' => true,
'sremove' => true,
'linsert' => true,
'hincrby' => true,
'flushdb' => true,
'migrate' => true,
'hgetall' => false,
'unwatch' => true,
'hexists' => false,
'zdelete' => false,
'discard' => true,
'getkeys' => false,
'persist' => true,
'setrange' => true,
'renamenx' => true,
'getrange' => false,
'bitcount' => false,
'smembers' => true,
'expireat' => true,
'lastsave' => true,
'listtrim' => true,
'flushall' => true,
'zrevrank' => false,
'sismember' => false,
'zrevrange' => false,
'randomkey' => false,
'rpoplpush' => true,
'scontains' => false,
'lgetrange' => false,
'renamekey' => true,
'sdiffstore' => true,
'settimeout' => true,
'sgetmembers' => true,
'sinterstore' => true,
'srandmember' => false,
'sunionstore' => true,
'getmultiple' => false,
'bgrewriteaof' => true,
'zrangebyscore' => false,
'zrevrangebyscore' => false,
'zremrangebyscore' => true,
'zdeleterangebyscore' => true,
); private function __construct()
{
} /**
* redis初始化
* 配置
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
* $array = array(
* 'master' => array(
* "redis://127.0.0.1:6379?timeout=1",
* ),
* 'slave' => array(
* "redis://127.0.0.1:6479?timeout=1",
* "redis://127.0.0.1:6579?timeout=1",
* )
* );
*
* $redis = RedisServer::instance($array);
*
* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*
*
*
* @param array $configs
* @return null|RedisServer
*/
public static function instance(array $configs)
{
if (self::$instance === null) {
self::$instance = new self();
foreach ($configs['master'] as $master) {
$connect = self::$instance->parseStr($master);
self::$instance->addMaster($connect[0], $connect[1], $connect[2]);
}
foreach ($configs['slave'] as $master) {
$connect = self::$instance->parseStr($master);
self::$instance->addSlave($connect[0], $connect[1], $connect[2]);
}
}
return self::$instance;
} private function parseStr($string)
{
$urls = parse_url($string);
$array[] = $urls['host'];
$array[] = isset($urls['port']) ? $urls['port'] : 6379;
$array[] = 1;
return $array;
} public function addMaster($host, $port = 6379, $timeout = 0.0)
{
self::$masterLength++;
self::$serverConfigs['master'][] = [$host, $port, $timeout];
} public function addSlave($host, $port = 6379, $timeout = 0.0)
{
self::$slaveLength++;
self::$serverConfigs['slave'][] = [$host, $port, $timeout];
} /**
* @param null $key
* @param bool|true $isMaster
* @return \Redis
*/
protected function getRedis($key = null, $isMaster = true)
{
empty($key) && $key = uniqid(true);
list($length, $server) = $isMaster ? [self::$masterLength, &self::$masterServers] : [self::$slaveLength, &self::$slaveServers];
$index = $this->getHostByHash($key, $length);
if (!isset($server[$index])) {
$connect = $isMaster ? self::$serverConfigs['master'][$index] : self::$serverConfigs['slave'][$index];
$server[$index] = new \Redis();
$server[$index]->connect($connect[0], $connect[1], $connect[2]);
if (self::$dbIndex !== null) {
$server[$index]->select($index);
}
/*if (!$isMaster) {
$server[$index]->slaveof(self::$serverConfigs['master'][0][0], self::$serverConfigs['master'][0][1]);
}*/
}
return $server[$index];
} private function getHostByHash($key, $n)
{
if ($n < 2) return 0;
$id = sprintf("%u", crc32($key));
$m = base_convert(intval(fmod($id, $n)), 10, $n);
return $m{0};
} public function __call($method, $args)
{
if (in_array(strtolower($method), self::$prohibitMap)) {
$this->prohibit($method);
} elseif (isset(self::$methodMap[strtolower($method)])) {
return call_user_func_array(array($this->getRedis(null, self::$methodMap[strtolower($method)]), $method), $args);
}
trigger_error("Call to undefined method " . __CLASS__ . "::{$method}() ", E_USER_ERROR);
} /**
* 禁用slaveof方法
*/
private function prohibit($method)
{
trigger_error("Call to prohibit access method " . __CLASS__ . "::{$method}() ", E_USER_ERROR);
} public function select($dbIndex)
{
foreach (self::$masterServers as &$master) {
$master->select($dbIndex);
}
unset($master);
foreach (self::$slaveServers as &$slave) {
$slave->select($dbIndex);
}
self::$dbIndex = $dbIndex;
unset($slave);
} }