Skip to content

Commit 9000dad

Browse files
committed
Redis 主从复制Master和Slave
1 parent 1a63fd7 commit 9000dad

File tree

1 file changed

+127
-0
lines changed

1 file changed

+127
-0
lines changed
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
<?php
2+
/**
3+
* Created by PhpStorm.
4+
* User: Tinywan
5+
* Date: 2016/11/1
6+
* Time: 8:54
7+
8+
*/
9+
10+
namespace Org\Util;
11+
12+
13+
class RedisInstance
14+
{
15+
/**
16+
* 类对象实例数组,共有静态变量
17+
* @var null
18+
*/
19+
private static $_instance;
20+
/**
21+
* 数据库连接资源句柄
22+
* @var
23+
*/
24+
private static $_connectSource;
25+
/**
26+
* 私有化构造函数,防止类外实例化
27+
* RedisConnect constructor.
28+
*/
29+
private function __construct()
30+
{
31+
}
32+
/**
33+
* 单例方法,用于访问实例的公共的静态方法
34+
* 这个只是一个实例
35+
* 这个实例方法适合于连接到别的Redis数据库中去。列如:在项目中选择不同的Redis数据库
36+
* @return \Redis
37+
* @static
38+
*/
39+
public static function Instance()
40+
{
41+
try{
42+
if (!(static::$_instance instanceof \Redis)) {
43+
static::$_instance = new \Redis();
44+
}
45+
return static::$_instance;
46+
}catch (\Exception $e){
47+
return false;
48+
}
49+
}
50+
/**
51+
* 单例方法,用于访问Master实例的公共的静态方法
52+
* @return \Redis
53+
* @static
54+
*/
55+
public static function MasterInstance()
56+
{
57+
try{
58+
self::Instance()->connect('121.41.88.209', '63789');
59+
self::Instance()->auth('tinywanredis');
60+
return static::$_instance;
61+
}catch (\Exception $e){
62+
return false;
63+
}
64+
}
65+
/**
66+
* Slave1 实例
67+
* @return null
68+
* @static
69+
*/
70+
public static function SlaveOneInstance()
71+
{
72+
try{
73+
self::Instance()->connect('121.41.88.209', '63788');
74+
return static::$_instance;
75+
}catch (\Exception $e){
76+
return false;
77+
}
78+
}
79+
/**
80+
* Slave2 实例
81+
* @return null
82+
* @static
83+
*/
84+
public static function SlaveTwoInstance()
85+
{
86+
try{
87+
self::Instance()->connect('121.41.88.209', '63700');
88+
return static::$_instance;
89+
}catch (\Exception $e){
90+
return false;
91+
}
92+
}
93+
/**
94+
* Redis数据库是否连接成功
95+
* @return bool|string
96+
*/
97+
public static function connect()
98+
{
99+
// 如果连接资源不存在,则进行资源连接
100+
if (!self::$_connectSource)
101+
{
102+
//@return bool TRUE on success, FALSE on error.
103+
self::$_connectSource = self::Instance()->connect('121.41.88.209', '63789');
104+
// 没有资源返回
105+
if (!self::$_connectSource)
106+
{
107+
return 'Redis Server Connection Fail';
108+
}
109+
}
110+
return self::$_connectSource;
111+
}
112+
/**
113+
* 私有化克隆函数,防止类外克隆对象
114+
*/
115+
private function __clone()
116+
{
117+
// TODO: Implement __clone() method.
118+
}
119+
/**
120+
* @return \Redis
121+
* @static
122+
*/
123+
public static function test()
124+
{
125+
return 'test';
126+
}
127+
}

0 commit comments

Comments
 (0)