Пример #1
0
 public function __construct($config = '')
 {
     if (empty($config)) {
         $config = Zc::C(ZcConfigConst::DbConfig);
     }
     $this->config = $config;
     // 初始化DB缓存
     if (isset($this->config['db_cache'])) {
         $cc = $this->config['db_cache'];
         $this->cache = Zc::getCache($cc['biz_name'], $cc['cache_type'], $cc['timestamp'], $cc['options']);
     }
     // 重新计算分布式DB的配置和权重
     foreach ($this->config['connections'] as $groupName => &$groupConfig) {
         $this->groupMapping[$groupName]['master'] = array('role' => 'master', 'db_id' => $groupConfig['master']['db_id'], 'read_weight' => isset($groupConfig['master']['read_weight']) ? $groupConfig['master']['read_weight'] : false);
         $this->dbIdMapping[$groupConfig['master']['db_id']] =& $groupConfig['master'];
         $this->dbIdMapping[$groupConfig['master']['db_id']]['role'] = 'master';
         if (!empty($groupConfig['slaves'])) {
             foreach ($groupConfig['slaves'] as &$slaveConfig) {
                 $this->dbIdMapping[$slaveConfig['db_id']] =& $slaveConfig;
                 $this->dbIdMapping[$slaveConfig['db_id']]['role'] = 'slave';
                 $this->groupMapping[$groupName][] = array('role' => 'slave', 'db_id' => $slaveConfig['db_id'], 'read_weight' => isset($slaveConfig['read_weight']) ? $slaveConfig['read_weight'] : false);
             }
         }
     }
     //重新计算下每台机器要分配的读权重
     foreach ($this->groupMapping as $groupName => &$group) {
         $countWeight = 0;
         $setCount = 0;
         foreach ($group as &$host) {
             if ($host['read_weight'] !== false) {
                 $setCount++;
             }
             $countWeight += $host['read_weight'];
         }
         if ($setCount === 0) {
             $setCount = count($group);
             $countWeight = 100;
         }
         $unsetWeight = (int) ($countWeight / $setCount);
         $currValve = 0;
         foreach ($group as &$host) {
             if ($host['read_weight'] === false) {
                 $host['read_weight'] = $unsetWeight;
             }
             $currValve += $host['read_weight'];
             $host['read_valve'] = $currValve;
         }
         $this->groupMaxValve[$groupName] = $currValve;
     }
 }