Store.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. /**
  3. *
  4. * 这里用php数组文件来存储数据,
  5. * 为了获取高性能需要用类似memcache、redis的存储
  6. * @author walkor <workerman.net>
  7. *
  8. */
  9. class Store
  10. {
  11. // 为了避免频繁读取磁盘,增加了缓存机制
  12. protected static $dataCache = array();
  13. // 上次缓存时间
  14. protected static $lastCacheTime = 0;
  15. // 保存数据的文件相对与WORKERMAN_LOG_DIR目录目录
  16. protected static $dataFile = 'data.php';
  17. // 打开文件的句柄
  18. protected static $dataFileHandle = null;
  19. // 缓存过期时间
  20. const CACHE_EXP_TIME = 1;
  21. public static function set($key, $value, $ttl = 0)
  22. {
  23. self::readDataFromDisk();
  24. self::$dataCache[$key] = $value;
  25. return self::writeToDisk();
  26. }
  27. public static function get($key, $use_cache = true)
  28. {
  29. if(time() - self::$lastCacheTime > self::CACHE_EXP_TIME)
  30. {
  31. self::readDataFromDisk();
  32. }
  33. return isset(self::$dataCache[$key]) ? self::$dataCache[$key] : null;
  34. }
  35. public static function delete($key)
  36. {
  37. self::readDataFromDisk();
  38. unset(self::$dataCache[$key]);
  39. return self::writeToDisk();
  40. }
  41. public static function deleteAll()
  42. {
  43. self::$dataCache = array();
  44. self::writeToDisk();
  45. }
  46. protected static function writeToDisk()
  47. {
  48. $data_file = WORKERMAN_LOG_DIR . self::$dataFile;
  49. if(!self::$dataFileHandle)
  50. {
  51. if(!is_file($data_file))
  52. {
  53. touch($data_file);
  54. }
  55. self::$dataFileHandle = fopen($data_file, 'r+');
  56. if(!self::$dataFileHandle)
  57. {
  58. return false;
  59. }
  60. }
  61. flock(self::$dataFileHandle, LOCK_EX);
  62. $ret = file_put_contents($data_file, "<?php \n return " . var_export(self::$dataCache, true). ';');
  63. flock(self::$dataFileHandle, LOCK_UN);
  64. return $ret;
  65. }
  66. protected static function readDataFromDisk()
  67. {
  68. $data_file = WORKERMAN_LOG_DIR . self::$dataFile;
  69. if(!is_file($data_file))
  70. {
  71. touch($data_file);
  72. }
  73. $cache = include WORKERMAN_LOG_DIR . self::$dataFile;
  74. if(is_array($cache))
  75. {
  76. self::$dataCache = $cache;
  77. }
  78. self::$lastCacheTime = time();
  79. }
  80. }