Store.php 2.8 KB

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