CacheConnectionManager.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. <?php
  2. class LtCacheConnectionManager
  3. {
  4. public $configHandle;
  5. protected $connectionAdapter;
  6. public function getConnection($group, $node, $role)
  7. {
  8. if ($connection = $this->getNewConnection($group, $node, $role))
  9. {
  10. return array(
  11. "connectionAdapter" => $this->connectionAdapter,
  12. "connectionResource" => $connection
  13. );
  14. }
  15. else
  16. {
  17. trigger_error("no cache server can be connected");
  18. return false;
  19. }
  20. }
  21. protected function getNewConnection($group, $node, $role)
  22. {
  23. $servers = $this->configHandle->get("cache.servers");
  24. $hostTotal = count($servers[$group][$node][$role]);
  25. $hostIndexArray = array_keys($servers[$group][$node][$role]);
  26. while ($hostTotal)
  27. {
  28. $hashNumber = substr(microtime(),7,1) % $hostTotal;
  29. $hostConfig = $servers[$group][$node][$role][$hostIndexArray[$hashNumber]];
  30. $cacheFactory = new LtCacheAdapterFactory;
  31. $this->connectionAdapter = $cacheFactory->getConnectionAdapter($hostConfig["adapter"]);
  32. if ($connection = $this->connectionAdapter->connect($hostConfig))
  33. {
  34. return $connection;
  35. }
  36. else
  37. {
  38. //trigger_error('connection fail', E_USER_WARNING);
  39. //delete the unavailable server
  40. for ($i = $hashNumber; $i < $hostTotal - 1; $i ++)
  41. {
  42. $hostIndexArray[$i] = $hostIndexArray[$i+1];
  43. }
  44. unset($hostIndexArray[$hostTotal-1]);
  45. $hostTotal --;
  46. }//end else
  47. }//end while
  48. return false;
  49. }
  50. }