【问题标题】:LRUCacheStrategy in Poco - how does it work?Poco 中的 LRU 缓存策略 - 它是如何工作的?
【发布时间】:2013-04-17 12:00:45
【问题描述】:
    void onAdd(const void*, const KeyValueArgs <TKey, TValue>& args)
{
    _keys.push_front(args.key());
    std::pair<IndexIterator, bool> stat = _keyIndex.insert(std::make_pair(args.key(), _keys.begin()));
    if (!stat.second)
    {
        stat.first->second = _keys.begin();
    }
}

有人能解释一下这段代码是如何工作的吗?它来自 POCO LRUCacheStrategy,它使用映射来实现 LRUCache。

我们想要更改缓存以在关闭时将其缓存对象存储到磁盘...我们可以在策略中添加一些文件流吗?

感谢您的帮助!

【问题讨论】:

    标签: c++ caching poco-libraries


    【解决方案1】:

    使用类似this 的方式序列化缓存映射并使用 fstream 存储/读取它。

    【讨论】:

      【解决方案2】:

      我们想要更改缓存,以便在关闭时将其缓存的对象存储到磁盘中

      没有显式缓存 close() (因此,没有策略 onClose() )调用,但您可以轻松创建自己的缓存(见下文)并自动在析构函数中持久化(重要:确保防止转义析构函数的任何异常)。

      定义你自己的缓存很简单,这是一个修改了析构函数的 LRUCache:

      template <
          class TKey, 
          class TValue,
          class TMutex = FastMutex, 
          class TEventMutex = FastMutex
      > 
      class PersistentLRUCache: public Poco::AbstractCache<TKey, TValue, LRUStrategy<TKey, TValue>, TMutex, TEventMutex>
      {
      public:
          // ...
      
          ~PersistentLRUCache()
          {
                  try {
                          Iterator it = _data.begin();
                          Iterator end = _data.end();
                          for (; it != end; ++it)
                          {
                              // write entries to file
                          }
                  } catch (...) { /* log errors */}
          }
      
          // ...
      };
      

      访问父类(受保护的)成员有点“脏”(如果框架为底层容器提供 begin() 和 end() 访问器会更好;无论好坏,它都是允许的,您可以利用它。

      我们可以在策略中添加一些文件流吗?

      将功能直接添加到框架类意味着您的更改将被每个新版本覆盖,您将不得不重新应用您的更改。最好按照上面所示定义自己的缓存,这样可以保护您免受框架更改覆盖您的功能。

      【讨论】:

      • 我认为_data是包含键和值的映射?
      • _data 是AbstractCache::_data,父类的受保护成员。
      猜你喜欢
      • 2018-02-14
      • 2012-03-28
      • 1970-01-01
      • 2011-10-15
      • 2015-06-23
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-26
      相关资源
      最近更新 更多