缓存在后台开发中是经常使用的,通常有通用的缓存服务,开源的有memcache, redis, 但是在数据量不是特别大,性能要求极高的情况,以及减少搭建和维护专门的缓存服务的成本,本地缓存具有很好的性能以及减少运维成本,本地缓存可以显著的减少网络开销,带来更高的性能,还可以避免缓存服务单点问题 ,下面是自己封装的一个基于LRU缓存淘汰算法的多线程安全LRU缓存组件,已经在项目中使用,性能比memcache高出很多。
/***************************************
function: local lru cache
author: liuyi
date: 2018.07.26
version: 2.0
****************************************/
#ifndef LOCAL_CACHE_H
#define LOCAL_CACHE_H
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <vector>
#include <map>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
using namespace std;
static int max_sleep_time = 2;
static int max_traversal_count = 10;
template<class T1, class T2>
class local_cache
{
public:
struct cache_data
{
time_t begin_time;
int expire_time;
T2 data;
};
local_cache()
{
}
~local_cache()
{
}
static void* lru_thread(void *args)
{
local_cache *p = (local_cache*)(args);
while(1)
{
sleep(max_sleep_time);
int count = p->lru_remove(max_traversal_count);
}
return NULL;
}
int lru_remove(int max_traversal_count)
{
int count = 0;
vector<int> rand_map_index_vect;
get_rand_map_index(m_multi_map_vect.size()/8 + 1, rand_map_index_vect);
for(size_t i = 0; i < rand_map_index_vect.size(); i++)
{
size_t index = rand_map_index_vect[i];
pthread_mutex_lock(m_multi_map_vect[index].second);
if(m_multi_map_vect[index].first->size() >= (m_slot_max_size / 2));
{
typename map<T1, cache_data>::iterator it = m_multi_