$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);
} }

php封装redis负载均衡类的更多相关文章

  1. net core 实战之 redis 负载均衡和"高可用"实现

    net core 实战之 redis 负载均衡和"高可用"实现 1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的& ...

  2. nginx+tomcat+redis负载均衡及session共享

    概述 本文档是用来详细描述 nginx+tomcat+redis负载均衡实现session共享 所需软件及下载地址 软件名称 下载地址 功能说明 Nginx-v1.6.0 http://nginx.o ...

  3. asp.net core 实战之 redis 负载均衡和"高可用"实现

    1.概述 分布式系统缓存已经变得不可或缺,本文主要阐述如何实现redis主从复制集群的负载均衡,以及 redis的"高可用"实现, 呵呵双引号的"高可用"并不是 ...

  4. nginx之 nginx + tomcat + redis 负载均衡且session一致性

    说明: 本文描述的是 nginx + tomcat + redis 实现应用负载均衡且满足session一致性,从安装到配置的全部过程,供大家学习!nginx 代理服务器ip: 10.219.24.2 ...

  5. redis 负载均衡 集群配置

    redis 官网 http://redis.io/ 中文网站 http://redis.cn/ 谷歌代码的redis项目 https://code.google.com/p/redis/ http:/ ...

  6. PHP redis负载均衡代码

    <?php /** * This is a Redis exntend class * jay.w */ class RedisClient { public static $instance ...

  7. Spring Cloud(Dalston.SR5)--Ribbon 中间层负载均衡

    Spring Cloud 集成了 Ribbon 并结合 Eureka 可以实现客户端的负载均衡,使用 @LoadBalanced 修饰的 RestTemplate 类拥有了负载均衡功能,在 Sprin ...

  8. 学习一下 SpringCloud (三)-- 服务调用、负载均衡 Ribbon、OpenFeign

    (1) 相关博文地址: 学习一下 SpringCloud (一)-- 从单体架构到微服务架构.代码拆分(maven 聚合): https://www.cnblogs.com/l-y-h/p/14105 ...

  9. 负载均衡session共享问题

    负载均衡+session共享(memcached-session-manager实现) http://www.cnblogs.com/youzhibing/p/5094460.html http:// ...

随机推荐

  1. 导入android项目在eclipse中会报@Override错误

    很多时候导入android项目在eclipse中会报@Override错误,这是由于java编译器的版本不正确,Java 1.5的编译器默认对父类的方法进行覆盖,采用@Override进行说明:但1. ...

  2. Js之History对象

    Window对象的history属性引用的是该窗口的History对象.History对象是用来把窗口的浏览历史用文档和文档状态列表的形式表示.History对象的length属牲表示浏览历史列表中的 ...

  3. [转]Cocos2d-x建工程时避免copy文件夹和库

    原文链接:  http://www.cnblogs.com/andyque/archive/2011/09/27/2192920.html 在上一篇教程中,我们演示了如何使用VS2010来新建一个工程 ...

  4. Sumblime Text 2 常用插件以及安装方法

    1.直接安装 安装Sublime text 2插件很方便,可以直接下载安装包解压缩到Packages目录(菜单->preferences->packages). 2.使用Package C ...

  5. 搜索打表大找规律 (hdu2045)

    不容易系列之(3)—— LELE的RPG难题 Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/O ...

  6. “弹出DVD驱动器错误”解决方法

    错误描述:(win7环境) 买了个开发板,赠送了一些光盘,放在电脑光驱中打开后,电脑就疯狂响,可能是光盘质量太差.用完后在弹出时显示“弹出DVD驱动器错误”[见图1].直接按主机上弹出按钮也没有反应. ...

  7. 基于方法的LINQ语句

    LINQ中的查询方法有两站,一种是使用类似于SQL语句的方式,另一种则是基于方法的语句.基于方法的查询方法使用的是C#中面向对象概念的,主要的方法有: 投影:  Select | SelectMany ...

  8. information_schema.partitions 学习

    1.partitions 表中的常用列说明: 1.table_schema:表所在的数据库名 2.table_name:表名 3.partition_method:表分区采用的分区方法 4.parti ...

  9. g++ error: extra qualification on member [-fpermissive]

    以下这段代码是在头文件里面的,DmaOpen DmaClose函数也是直接在class pcie_chip{}里面的.加了个额外的pcie_chip::才会报错. //delete pcie_chip ...

  10. [转]UltraISO制作U盘启动盘安装Win7/9/10系统攻略

    原文地址:http://www.cnblogs.com/pchmonster/p/4716708.html U盘安装好处就是不用使用笨拙的光盘,光盘还容易出现问题,无法读取的问题.U盘体积小,携带方便 ...