Store.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. /**
  3. * This file is part of workerman.
  4. *
  5. * Licensed under The MIT License
  6. * For full copyright and license information, please see the MIT-LICENSE.txt
  7. * Redistributions of files must retain the above copyright notice.
  8. *
  9. * @author walkor<walkor@workerman.net>
  10. * @copyright walkor<walkor@workerman.net>
  11. * @link http://www.workerman.net/
  12. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  13. */
  14. namespace GatewayWorker\Lib;
  15. /**
  16. * 存储类
  17. * 这里用memcache实现
  18. */
  19. class Store
  20. {
  21. /**
  22. * 实例数组
  23. * @var array
  24. */
  25. protected static $instance = array();
  26. /**
  27. * 获取实例
  28. * @param string $config_name
  29. * @throws \Exception
  30. */
  31. public static function instance($config_name)
  32. {
  33. // memcached 驱动
  34. if(\Config\Store::$driver == \Config\Store::DRIVER_MC)
  35. {
  36. if(!isset(\Config\Store::$$config_name))
  37. {
  38. echo "\\Config\\Store::$config_name not set\n";
  39. throw new \Exception("\\Config\\Store::$config_name not set\n");
  40. }
  41. if(!isset(self::$instance[$config_name]))
  42. {
  43. if(extension_loaded('Memcached'))
  44. {
  45. self::$instance[$config_name] = new \Memcached;
  46. }
  47. elseif(extension_loaded('Memcache'))
  48. {
  49. self::$instance[$config_name] = new \Memcache;
  50. }
  51. else
  52. {
  53. sleep(2);
  54. exit("extension memcached is not installed\n");
  55. }
  56. foreach(\Config\Store::$$config_name as $address)
  57. {
  58. list($ip, $port) = explode(':', $address);
  59. self::$instance[$config_name] ->addServer($ip, $port);
  60. }
  61. }
  62. return self::$instance[$config_name];
  63. }
  64. // redis 驱动
  65. elseif(\Config\Store::$driver == \Config\Store::DRIVER_REDIS)
  66. {
  67. if(!isset(\Config\Store::$$config_name))
  68. {
  69. echo "\\Config\\Store::$config_name not set\n";
  70. throw new \Exception("\\Config\\Store::$config_name not set\n");
  71. }
  72. if(!isset(self::$instance[$config_name]))
  73. {
  74. self::$instance[$config_name] = new \GatewayWorker\Lib\StoreDriver\Redis();
  75. // 只选择第一个ip作为服务端
  76. $address = current(\Config\Store::$$config_name);
  77. list($ip, $port) = explode(':', $address);
  78. $timeout = 1;
  79. self::$instance[$config_name]->connect($ip, $port, $timeout);
  80. self::$instance[$config_name]->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
  81. }
  82. return self::$instance[$config_name];
  83. }
  84. // 文件驱动
  85. else
  86. {
  87. if(!isset(self::$instance[$config_name]))
  88. {
  89. self::$instance[$config_name] = new \GatewayWorker\Lib\StoreDriver\File($config_name);
  90. }
  91. return self::$instance[$config_name];
  92. }
  93. }
  94. }