LruCache的代码实现,以及分析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_22054285/article/details/86673393

LruCache的代码实现以及分析

简介

作为存储数据、获取数据的服务,LruCache被大量的广泛使用。例如,我们在redis、mongodb种存储海量的数据,应用服务通过api通过网络进行存取,但是由于二八原则,我们大多数情况下,获取的都是相同的一批数据,所以这个时候可以在服务内存创建LruCache将数据进行缓存。

原理

  1. 当数据请求到来的时候,首先访问内存的cache,如果内存中没有,则通过网络远程访问存储。
  2. 获取数据后,将数据写入到缓存中,同时在list中更新位置到队列的同步;
  3. 如果cache中找到的话,返回用户数据,然后同时更新数据在list中的位置。

源代码

#include <unordered_map>
#include <string>
#include <list>

using namespace std;

class LRUCache
{
	public:
		struct CacheEntry
		{
			public:
				int key;
				int value;
				CacheEntry(int k, int v) :key(k), value(v) {}
		};

		LRUCache(int capacity) {
			m_capacity = capacity;
		}
		
		int get(int key) {
			if (m_map.find(key) == m_map.end())
				return -1;

			MoveToHead(key);
			return m_map[key]->value;
		}

		void put(int key, int value) 
		{
			if (m_map.find(key) == m_map.end()){
				CacheEntry newItem(key, value);
				if (m_LRU_cache.size() >= m_capacity)
				{
					//remove from tail
					m_map.erase(m_LRU_cache.back().key);
					m_LRU_cache.pop_back();                
				}
				// insert in head.
				m_LRU_cache.push_front(newItem);
				m_map[key] = m_LRU_cache.begin();
				return;
			}
		 	m_map[key]->value = value;
			MoveToHead(key);
	  }

	private:
		unordered_map<int, list<CacheEntry>::iterator> m_map;
		list<CacheEntry> m_LRU_cache;
		int m_capacity;

		void MoveToHead(int key) 
		{
			//Move key from current location to head
			auto updateEntry = *m_map[key];
			m_LRU_cache.erase(m_map[key]);
			m_LRU_cache.push_front(updateEntry);
			m_map[key] = m_LRU_cache.begin();
	}
 };

int main(int argc, char ** argb)
{
    LRUCache* obj = new LRUCache(2);
    obj->put(1,1);
    obj->get(1);
    return 0;
}

优化点

  • cache基于lru,如果每条数据在远程存储已经修改,但是在cache中由于反复使用,所以一直无法更新;解决办法:给cache设置个超时时间;
  • 同步锁:在多线程的情况下,锁的冲突会很大,这个时候需要考虑使用多个锁来降低锁的冲突。

总结

本文介绍了一个非常简单的lru的实现,有兴趣的读者可以自己扩展。

猜你喜欢

转载自blog.csdn.net/qq_22054285/article/details/86673393