本文實例講述了Laravel框架實現(xiàn)redis集群的方法。分享給大家供大家參考,具體如下:
在app/config/database.php中配置如下:
'redis' => array( 'cluster' => true, 'default' => array( 'host' => '172.21.107.247', 'port' => 6379, ), 'redis1' => array( 'host' => '172.21.107.248', 'port' => 6379, ),
其中cluster選擇為true,接下來就可以作集群使用了;
如果把session的driver設(shè)置為redis,則可以使用其集群功能了:
我們來看下session的實現(xiàn),當我們在代碼中這樣寫:
Session::put('test', 124);
實際的執(zhí)行流程是這樣的:
IlluminateSupportFacadesSession IlluminateSupportFacadesFacade IlluminateSessionFacade::app['session']->put IlluminateSessionFacade::app['session']為IlluminateSessionSessionManager IlluminateSupportManager::__call
Session會根據(jù)返回創(chuàng)建driver
$this->app['config']['session.driver']
即配置文件中配置的,這里我們配置為redis
IlluminateSessionSessionManager::IlluminateSessionSessionManager
最終由IlluminateSessionStore來負責put的調(diào)用
而Store類負責存儲的類是IlluminateSessionCacheBasedSessionHandler
后者又將請求轉(zhuǎn)發(fā)給$this->app['cache']->driver($driver)
……
經(jīng)過一系列代碼追查,存儲類為PredisClientDatabase,看其構(gòu)造函數(shù):
public function __construct(array $servers = array()) { if (isset($servers['cluster']) && $servers['cluster']) { $this->clients = $this->createAggregateClient($servers); } else { $this->clients = $this->createSingleClients($servers); } }
如果設(shè)置為集群,則調(diào)用createAggregateClient方法
protected function createAggregateClient(array $servers) { $servers = array_except($servers, array('cluster')); return array('default' => new Client(array_values($servers))); }
這里會把所有服務器放在default組中
實際存數(shù)據(jù)的類是PredisClient,這里有根據(jù)配置創(chuàng)建服務器的代碼,具體可以自己看下;
PredisClusterPredisClusterHashStrategy類負責計算key的hash,關(guān)鍵函數(shù):
getHash
getKeyFromFirstArgument
而PredisClusterDistributionHashRing負責服務器環(huán)的維護,關(guān)鍵函數(shù)
addNodeToRing
get
hash
大概原理是這樣,如執(zhí)行以下redis命令
get ok
會將ok作crc32運算得到一個hash值
所有服務器按一定算法放到一個長度默認為128的數(shù)組中,每個服務器在其中占幾項,由以下決定:
權(quán)重/總權(quán)重*總的服務器數(shù)量*128,可參考PredisClusterDistributionHashRing::addNodeToRing方法
每一項的hash值是按服務器ip:端口的格式,作crc32計算的
protected function addNodeToRing(&$ring, $node, $totalNodes, $replicas, $weightRatio) { $nodeObject = $node['object']; $nodeHash = $this->getNodeHash($nodeObject); $replicas = (int) round($weightRatio * $totalNodes * $replicas); for ($i = 0; $i < $replicas; $i++) { $key = crc32("$nodeHash:$i"); $ring[$key] = $nodeObject; } }
key的hash值也有了,服務器環(huán)也計算好了,剩下的就是查找了,二分法能較快的查找相應的服務器節(jié)點
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。