fastdo  0.6.16
http_StaticFileMemoryCache.hpp
浏览该文件的文档.
1 #pragma once
2 
3 namespace http
4 {
5 
8 {
9 public:
10  struct CacheItem
11  {
12  time_t timeStamp;
15  };
16 
17  // map< name, cache_item >
18  typedef std::map< winux::String, CacheItem > CacheItemsMap;
19 
20  // 构造函数
21  StaticFileMemoryCache( time_t lifeTime = 0 ) : _cacheLifeTime(lifeTime), _mtxCache(true)
22  {
23  }
24 
25  bool hasCache( winux::String const & cacheName ) const
26  {
27  if ( this->_cacheLifeTime < 1 ) //如果未开启缓存功能,直接返回false
28  {
29  return false;
30  }
31  if ( true )
32  {
33  winux::ScopeGuard guard( const_cast<winux::RecursiveMutex &>(_mtxCache) );
34  if ( winux::isset( this->_cacheItems, cacheName ) ) // 存在缓存
35  {
36  time_t cacheFileMTime = this->_cacheItems.at(cacheName).timeStamp; //取得最后修改时间
37  if ( cacheFileMTime + this->_cacheLifeTime >= winux::GetUtcTime() ) // 尚未过期
38  {
39  return true;
40  }
41  }
42  }
43  return false;
44  }
45 
46  CacheItem const & get( winux::String const & cacheName ) const
47  {
48  winux::ScopeGuard guard( const_cast<winux::RecursiveMutex &>(_mtxCache) );
49  return this->_cacheItems.at(cacheName);
50  }
51 
53  {
54  CacheItem * item = nullptr;
55  if ( true )
56  {
57  winux::ScopeGuard guard( const_cast<winux::RecursiveMutex &>(_mtxCache) );
58  item = &this->_cacheItems[cacheName];
59  item->timeStamp = winux::GetUtcTime();
60  item->mime = std::move(mime);
61  item->content = std::move(content);
62  }
63  return *item;
64  }
65 
66  void setLifeTime( time_t lifeTime = 0 )
67  {
68  this->_cacheLifeTime = lifeTime;
69  }
70 
71  time_t getLifeTime() const
72  {
73  return this->_cacheLifeTime;
74  }
75 private:
76  time_t _cacheLifeTime; // 缓存生命期 0表示不缓存
77  CacheItemsMap _cacheItems;
78  winux::RecursiveMutex _mtxCache;
79 };
80 
81 
82 } // namespace http
XString< tchar > String
Definition: utilities.hpp:261
bool hasCache(winux::String const &cacheName) const
HTTP协议的相关简单类封装
Definition: http_base.hpp:32
作用域范围保护
Definition: system.hpp:217
缓冲区,表示内存中一块二进制数据(利用malloc/realloc进行内存分配)
Definition: utilities.hpp:906
time_t GetUtcTime(void)
获取UTC时间秒数,或者调用CRT的time(NULL)
std::map< winux::String, CacheItem > CacheItemsMap
bool isset(_MAP const &m, _KEY const &k)
检测map中是否有该键的值
Definition: utilities.hpp:807
CacheItem & writeCache(winux::String const &cacheName, winux::String mime, winux::Buffer content)
静态文件内存缓存(带互斥锁)