BaseDB.class.php
12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
<?php
require_once dirname(__FILE__).'/config/common.inc.php';
abstract class Util_Db_BaseDB
{
public $mWDBConf = array();
public $mRDBConf = array();
private $mDBNameKey = array();
private $mSwitchFlag = false;
protected $mInstance = null;
private $mBackupInstance = array();
private $mBackupWriteFlag = array();
private $mBackupWeight = array();
private static $mCurrentDBName = '';
/**
* 初始化
*/
public function __construct($db_config=array())
{
if(empty($db_config))
{
require dirname(__FILE__).'/config/db.inc.php';
}
$this->mWDBConf = $db_config['master'];
$this->mDBNameKey = array_keys($this->mWDBConf);
$this->mRDBConf = $db_config['slave'];
if(!empty(self::$mCurrentDBName))
{
self::$mCurrentDBName = BASEDB_DEFAULTCONNECT_DBNAME;
}
}
/**
* 连接到主数据库服务器
*
* @param string $dbNameKey
* @return object
*/
public function conn_master($dbNameKey = BASEDB_DEFAULTCONNECT_DBNAME)
{
$host = $this->mWDBConf[$dbNameKey]['host'];
$user = $this->mWDBConf[$dbNameKey]['user'];
$pwd = $this->mWDBConf[$dbNameKey]['pwd'];
$dbname = $this->mWDBConf[$dbNameKey]['dbname'];
$port = $this->mWDBConf[$dbNameKey]['port'];
$link = new mysqli($host, $user, $pwd, $dbname, $port);
//echo "host: ".$host;
//error_log('master time: '.date('Y-m-d H:i:s', time())."\n", 3, dirname(__FILE__).'/dbaccess.log');
//error_log('master host: '.$host."\n", 3,dirname(__FILE__).'/dbaccess.log');
if(mysqli_connect_errno())
{
$link = false;
echo '<h2>'.mysqli_connect_error().'</h2>';
die();
}
else
{
$link->set_charset("utf8");
}
return $link;
}
/**
* 连接到从数据库服务器
*
* @param string $dbNameKey
* @return object
*/
public function conn_slave($dbNameKey = BASEDB_DEFAULTCONNECT_DBNAME)
{
$offset = $this->weightRandomDB($this->mRDBConf[$dbNameKey], $dbNameKey);
$host = $this->mRDBConf[$dbNameKey][$offset]['host'];
$user = $this->mRDBConf[$dbNameKey][$offset]['user'];
$pwd = $this->mRDBConf[$dbNameKey][$offset]['pwd'];
$dbName = $this->mRDBConf[$dbNameKey][$offset]['dbname'];
$port = $this->mRDBConf[$dbNameKey][$offset]['port'];
$link = new mysqli($host, $user, $pwd, $dbName, $port);
//如果连接失败
if(mysqli_connect_errno())
{
foreach($this->mRDBConf as $key=>$rDBConf)
{
if($key == $offset)
{
continue;
}
$host = $this->mRDBConf[$dbNameKey][$offset]['host'];
$user = $this->mRDBConf[$dbNameKey][$offset]['user'];
$pwd = $this->mRDBConf[$dbNameKey][$offset]['pwd'];
$databasename = $this->mRDBConf[$dbNameKey][$offset]['dbname'];
$port = $this->mRDBConf[$dbNameKey][$offset]['port'];
$link = new mysqli($host, $user, $pwd, $dbName, $port);
if(is_object($link))
{
break;
}
}
}
//都连接失败,自动切换到主库
if(!is_object($link))
{
return $this->conn_master($dbNameKey);
}
else
{
//error_log('slave time: '.date('Y-m-d H:i:s', time())."\n", 3, dirname(__FILE__).'/dbaccess.log');
//error_log('slave host: '.$this->mRDBConf[$dbNameKey][$offset]['host']."\n", 3, dirname(__FILE__).'/dbaccess.log');
//echo "host: ".$this->mRDBConf[$dbNameKey][$offset]['host'];
$link->set_charset("utf8");
return $link;
}
}
/**
*设置数据连接
*
* @param boolean $isMaster
* @return object
*/
public function setDefaultConnect($isMaster = true)
{
if($this->mSwitchFlag)
{
return;
}
if($isMaster)
{
$this->mBackupInstance[self::$mCurrentDBName] = $this->conn_master(self::$mCurrentDBName);
$this->mBackupWriteFlag[self::$mCurrentDBName] = true;
}
else
{
$this->mBackupInstance[self::$mCurrentDBName] = $this->conn_slave(self::$mCurrentDBName);
$this->mBackupWriteFlag[self::$mCurrentDBName] = false;
}
}
/**
* 设置服务器开关
*
* @param boolean $flag
* @return object
*/
public function setHostSwitch($flag = true)
{
$this->mSwitchFlag = $flag;
//设置当前的主库
if($flag)
{
$this->mInstance = $this->mBackupInstance[self::$mCurrentDBName];
}
}
/**
* 自动选择服务器
*
* @param string $sql
* @return object
*/
public function autoChoiseHost($sql)
{
if(!empty($sql))
{
$isMaster = $this->checkMaster($sql);
if(array_key_exists(self::$mCurrentDBName,$this->mBackupInstance) && is_object($this->mBackupInstance[self::$mCurrentDBName]))
{
//当前状态是读,判断执行操作是写
if($this->mBackupWriteFlag[self::$mCurrentDBName]!=$isMaster && $isMaster)
{
//关闭读连接
$this->mInstance->close();
//切换到主库
$this->setDefaultConnect(true);
$this->mInstance = $this->mBackupInstance[self::$mCurrentDBName];
}
//当前状态与执行操作相同返回
else if(($this->mBackupWriteFlag[self::$mCurrentDBName]==$isMaster))
{
return;
}
}
else
{
$this->setDefaultConnect($isMaster);
$this->mInstance = $this->mBackupInstance[self::$mCurrentDBName];
}
}
}
/**
* 检查主从
*
* @param string $sql
* @return boolean
*/
private function checkMaster($sql)
{
$sqls = explode(" ", ltrim($sql));
$optType = trim(strtolower($sqls[0]));
$matches = '';
$rules = array();
$dbName = '';
$state = 'read';
preg_match_all('@\/\*(.+)\*\/@isU',$sql,$matches);
$result = false;
if(isset($matches[1][0]))
{
$rules = json_decode(str_replace('\'','"', trim($matches[1][0])),true);
}
$potPos = strpos($sql,'.');
$quotePos = strpos($sql,'\'');
//判断第一次点出现位置,用于处理数据库关键字
if($potPos<$quotePos||($potPos>0&&$quotePos==false))
{
foreach($this->mDBNameKey as $dbNameKey)
{
$key = substr($sql,$potPos-strlen($dbNameKey),strlen($dbNameKey));
if(strcmp($key, $dbNameKey)==0)
{
self::$mCurrentDBName = $dbNameKey;
break;
}
}
}
else
{
self::$mCurrentDBName = BASEDB_DEFAULTCONNECT_DBNAME;
}
//注释规则
if(count($rules))
{
if(isset($rules['dbname']))
{
$dbName = strtolower($rules['dbname']);
}
if(isset($rules['state']))
{
$state = strtolower($rules['state']);
}
}
if(empty($dbName))
{
self::$mCurrentDBName = BASEDB_DEFAULTCONNECT_DBNAME;
}
else
{
self::$mCurrentDBName = $dbName;
}
if(strcmp($optType, 'call')==0)
{
if(strcmp($state,'read')==0)
{
//数据切分
if(isset($rules['segrule']))
{
self::$mCurrentDBName = $this->dataSegByRouter($sql, $rules['segrule'] ,false);
}
$result = false;
}
else
{
//数据切分
if(isset($rules['segrule']))
{
self::$mCurrentDBName = $this->dataSegByRouter($sql, $rules['segrule']);
}
$result = true;
}
}
else if(strcmp($optType,'select')==0)
{
//数据切分
if(isset($rules['segrule']))
{
self::$mCurrentDBName = $this->dataSegByRouter($sql, $rules['segrule'] ,false);
}
$result = false;
}
else
{
//数据切分
if(isset($rules['segrule']))
{
self::$mCurrentDBName = $this->dataSegByRouter($sql, $rules['segrule']);
}
$result = true;
}
return $result;
}
/**
* 加权随机选择
*
* @param array $slaveDBs
* @param string $dbNameKey
* @return string
*/
private function weightRandomDB($slaveDBs, $dbNameKey)
{
$slaveDBsCount = count($slaveDBs);
//位数
$median = strlen($slaveDBsCount);
$totalWeight = 0;
$sequence = 0;
if($slaveDBsCount)
{
if(empty($this->mBackupWeight[$dbNameKey]))
{
//序列
$this->mBackupWeight[$dbNameKey]['sequence'] = '';
//总权值
$this->mBackupWeight[$dbNameKey]['totalWeight'] = 0;
$weight = 0;
foreach($slaveDBs as $key=>$slaveDB)
{
if(isset($slaveDB['weight']))
{
$weight = intval($slaveDB['weight']);
}
$this->mBackupWeight[$dbNameKey]['totalWeight'] += $weight;
if(empty($weight))
{
continue;
}
$this->mBackupWeight[$dbNameKey]['sequence'] .= str_repeat(sprintf('%0'.$median.'s',$key), $weight);
}
}
$totalWeight = $this->mBackupWeight[$dbNameKey]['totalWeight'];
$sequence = $this->mBackupWeight[$dbNameKey]['sequence'];
//判断总权是否为0
if(empty($totalWeight))
{
$key = rand(0, $slaveDBsCount-1);
}
else
{
$keyPos = rand(0, $totalWeight-1)*$median;
$key = intval(substr($sequence, $keyPos, $median));
}
return $key;
}
}
/**
* 数据切分根据路由选择数据库
* 条件:
*
* 1. 统一放在第一个sql关键字词语后面,用空格分开。
2. json里面都的关键字变量统一都用小写方式。
3. json里面标识关键字的双引号,用单引号表示
* 参数:
* {'dbname':'','state':'','segrule':{'tablename':{'current':'','seg':''},
* 'readdbs':[],'writedbs':[],'router':''}}
*
* dbname:数据库名
state:数据库状态:变量值: 为read 或write.
segrule:数据切分规则:(可以不写)
tablename:表名:
current:当前表名
seg:切分后的表名
readdbs:读数据库群,数组类型
writedbs写数据库群,数组类型
router:路由规则,根据路由规则实现数据切分,(没有具体相应的规则):参数里面:可以传递相应的函数列表。
* 根据router路由规则选择读写数据库
* 再对sql语句进行处理
* @param string &$sql
* @param array $segRule
* @param boolean $isWriteState
* @return String
*/
private function dataSegByRouter(&$sql, $segRule, $isWriteState = true)
{
if(empty($segRule))
{
return ;
}
else
{
//array
$tableName = $segRule['tablename'];
//array
$readDBs = $segRule['readdbs'];
//array
$writeDBs = $segRule['writedbs'];
//路由,todo
$router = $segRule['router'];
if($router && $isWriteState)
{
return $writeDBs[array_rand($writeDBs,1)];
}
else
{
return $readDBs[array_rand($readDBs,1)];
}
}
}
/**
* 析构
*/
public function __destruct()
{
foreach($this->mBackupInstance as $instance)
{
if(is_object($instance))
{
$instance->close();
}
}
unset($this->mBackupWriteFlag);
unset($this->mBackupWeight);
self::$mCurrentDBName = '';
}
}
?>