1
0

FileCache.h 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #ifndef HV_FILE_CACHE_H_
  2. #define HV_FILE_CACHE_H_
  3. #include <memory>
  4. #include <map>
  5. #include <string>
  6. #include <mutex>
  7. #include "hbuf.h"
  8. #include "hstring.h"
  9. #define HTTP_HEADER_MAX_LENGTH 1024 // 1K
  10. #define FILE_CACHE_MAX_SIZE (1 << 30) // 1G
  11. typedef struct file_cache_s {
  12. //std::string filepath;
  13. struct stat st;
  14. time_t open_time;
  15. time_t stat_time;
  16. uint32_t stat_cnt;
  17. HBuf buf; // http_header + file_content
  18. hbuf_t filebuf;
  19. hbuf_t httpbuf;
  20. char last_modified[64];
  21. char etag[64];
  22. const char* content_type;
  23. file_cache_s() {
  24. stat_cnt = 0;
  25. content_type = NULL;
  26. }
  27. bool if_modified(const char* filepath) {
  28. time_t mtime = st.st_mtime;
  29. stat(filepath, &st);
  30. if (mtime == st.st_mtime) {
  31. return false;
  32. }
  33. return true;
  34. }
  35. void resize_buf(int filesize) {
  36. buf.resize(HTTP_HEADER_MAX_LENGTH + filesize);
  37. filebuf.base = buf.base + HTTP_HEADER_MAX_LENGTH;
  38. filebuf.len = filesize;
  39. }
  40. void prepend_header(const char* header, int len) {
  41. if (len > HTTP_HEADER_MAX_LENGTH) return;
  42. httpbuf.base = filebuf.base - len;
  43. httpbuf.len = len + filebuf.len;
  44. memcpy(httpbuf.base, header, len);
  45. }
  46. } file_cache_t;
  47. typedef std::shared_ptr<file_cache_t> file_cache_ptr;
  48. // filepath => file_cache_ptr
  49. typedef std::map<std::string, file_cache_ptr> FileCacheMap;
  50. #define DEFAULT_FILE_STAT_INTERVAL 10 // s
  51. #define DEFAULT_FILE_EXPIRED_TIME 60 // s
  52. class FileCache {
  53. public:
  54. int file_stat_interval;
  55. int file_expired_time;
  56. FileCacheMap cached_files;
  57. std::mutex mutex_;
  58. FileCache() {
  59. file_stat_interval = DEFAULT_FILE_STAT_INTERVAL;
  60. file_expired_time = DEFAULT_FILE_EXPIRED_TIME;
  61. }
  62. file_cache_ptr Open(const char* filepath, bool need_read = true, void* ctx = NULL);
  63. bool Close(const char* filepath);
  64. bool Close(const file_cache_ptr& fc);
  65. void RemoveExpiredFileCache();
  66. protected:
  67. file_cache_ptr Get(const char* filepath);
  68. };
  69. #endif // HV_FILE_CACHE_H_