File.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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\StoreDriver;
  15. /**
  16. * 这里用php数组文件来存储数据,
  17. * 为了获取高性能需要用类似memcache的存储
  18. */
  19. class File
  20. {
  21. // 为了避免频繁读取磁盘,增加了缓存机制
  22. protected $dataCache = array();
  23. // 上次缓存时间
  24. protected $lastCacheTime = 0;
  25. // 打开文件的句柄
  26. protected $dataFileHandle = null;
  27. /**
  28. * 构造函数
  29. * @param 配置名 $config_name
  30. */
  31. public function __construct($config_name)
  32. {
  33. if(!is_dir(\Config\Store::$storePath) && !@mkdir(\Config\Store::$storePath, 0777, true))
  34. {
  35. // 可能目录已经被其它进程创建
  36. clearstatcache();
  37. if(!is_dir(\Config\Store::$storePath))
  38. {
  39. // 避免狂刷日志
  40. sleep(1);
  41. throw new \Exception('cant not mkdir('.\Config\Store::$storePath.')');
  42. }
  43. }
  44. $this->dataFileHandle = fopen(__FILE__, 'r');
  45. if(!$this->dataFileHandle)
  46. {
  47. throw new \Exception("can not fopen dataFileHandle");
  48. }
  49. }
  50. /**
  51. * 设置
  52. * @param string $key
  53. * @param mixed $value
  54. * @param int $ttl
  55. * @return number
  56. */
  57. public function set($key, $value, $ttl = 0)
  58. {
  59. return file_put_contents(\Config\Store::$storePath.'/'.$key, serialize($value), LOCK_EX);
  60. }
  61. /**
  62. * 读取
  63. * @param string $key
  64. * @param bool $use_cache
  65. * @return Ambigous <NULL, multitype:>
  66. */
  67. public function get($key, $use_cache = true)
  68. {
  69. $ret = @file_get_contents(\Config\Store::$storePath.'/'.$key);
  70. return $ret ? unserialize($ret) : null;
  71. }
  72. /**
  73. * 删除
  74. * @param string $key
  75. * @return number
  76. */
  77. public function delete($key)
  78. {
  79. return @unlink(\Config\Store::$storePath.'/'.$key);
  80. }
  81. /**
  82. * 自增
  83. * @param string $key
  84. * @return boolean|multitype:
  85. */
  86. public function increment($key)
  87. {
  88. flock($this->dataFileHandle, LOCK_EX);
  89. $val = $this->get($key);
  90. $val = !$val ? 1 : ++$val;
  91. file_put_contents(\Config\Store::$storePath.'/'.$key, serialize($val));
  92. flock($this->dataFileHandle, LOCK_UN);
  93. return $val;
  94. }
  95. /**
  96. * 清零销毁存储数据
  97. */
  98. public function destroy()
  99. {
  100. }
  101. }