first comit

This commit is contained in:
drygrass
2025-11-18 23:41:04 +08:00
commit 89351183c3
13 changed files with 2376 additions and 0 deletions

28
.gitignore vendored Normal file
View File

@@ -0,0 +1,28 @@
# CMake 生成目录
build/
CMakeFiles/
CMakeCache.txt
.cache/
.vscode/
.test
# CMake 生成的可执行文件和库
*.exe
*.out
*.a
*.so
*.dylib
*.lib
*.dll
# CMake 临时文件
*.cmake
Makefile
CMakeScripts/
# 其他常见生成文件
*.ninja
.ninja_deps
.ninja_log
compile_commands.json
install_manifest.txt

21
CMakeLists.txt Normal file
View File

@@ -0,0 +1,21 @@
# 设置最低 CMake 版本要求
cmake_minimum_required(VERSION 3.10)
# 设置项目名称
project(KCacheSystem)
# 设置 C++ 标准
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED True)
# 指定源文件目录下的所有 .cpp 文件
file(GLOB SOURCES "*.cpp")
# 设置目标可执行文件
add_executable(main ${SOURCES})
# 清理中间的 .o 文件
set_target_properties(main PROPERTIES CLEAN_DIRECT_OUTPUT 1)
# 额外的编译选项(可根据需要启用)
# target_compile_options(main PRIVATE -Wall -Wextra -O2)

92
KArcCache/KArcCache.h Normal file
View File

@@ -0,0 +1,92 @@
#pragma once
#include "../KICachePolicy.h"
#include "KArcLruPart.h"
#include "KArcLfuPart.h"
#include <memory>
namespace KamaCache
{
template<typename Key, typename Value>
class KArcCache : public KICachePolicy<Key, Value>
{
public:
explicit KArcCache(size_t capacity = 10, size_t transformThreshold = 2)
: capacity_(capacity)
, transformThreshold_(transformThreshold)
, lruPart_(std::make_unique<ArcLruPart<Key, Value>>(capacity, transformThreshold))
, lfuPart_(std::make_unique<ArcLfuPart<Key, Value>>(capacity, transformThreshold))
{}
~KArcCache() override = default;
void put(Key key, Value value) override
{
checkGhostCaches(key);
// 检查 LFU 部分是否存在该键
bool inLfu = lfuPart_->contain(key);
// 更新 LRU 部分缓存
lruPart_->put(key, value);
// 如果 LFU 部分存在该键,则更新 LFU 部分
if (inLfu)
{
lfuPart_->put(key, value);
}
}
bool get(Key key, Value& value) override
{
checkGhostCaches(key);
bool shouldTransform = false;
if (lruPart_->get(key, value, shouldTransform))
{
if (shouldTransform)
{
lfuPart_->put(key, value);
}
return true;
}
return lfuPart_->get(key, value);
}
Value get(Key key) override
{
Value value{};
get(key, value);
return value;
}
private:
bool checkGhostCaches(Key key)
{
bool inGhost = false;
if (lruPart_->checkGhost(key))
{
if (lfuPart_->decreaseCapacity())
{
lruPart_->increaseCapacity();
}
inGhost = true;
}
else if (lfuPart_->checkGhost(key))
{
if (lruPart_->decreaseCapacity())
{
lfuPart_->increaseCapacity();
}
inGhost = true;
}
return inGhost;
}
private:
size_t capacity_;
size_t transformThreshold_;
std::unique_ptr<ArcLruPart<Key, Value>> lruPart_;
std::unique_ptr<ArcLfuPart<Key, Value>> lfuPart_;
};
} // namespace KamaCache

41
KArcCache/KArcCacheNode.h Normal file
View File

@@ -0,0 +1,41 @@
#pragma once
#include <memory>
namespace KamaCache
{
template<typename Key, typename Value>
class ArcNode
{
private:
Key key_;
Value value_;
size_t accessCount_;
std::weak_ptr<ArcNode> prev_;
std::shared_ptr<ArcNode> next_;
public:
ArcNode() : accessCount_(1), next_(nullptr) {}
ArcNode(Key key, Value value)
: key_(key)
, value_(value)
, accessCount_(1)
, next_(nullptr)
{}
// Getters
Key getKey() const { return key_; }
Value getValue() const { return value_; }
size_t getAccessCount() const { return accessCount_; }
// Setters
void setValue(const Value& value) { value_ = value; }
void incrementAccessCount() { ++accessCount_; }
template<typename K, typename V> friend class ArcLruPart;
template<typename K, typename V> friend class ArcLfuPart;
};
} // namespace KamaCache

231
KArcCache/KArcLfuPart.h Normal file
View File

@@ -0,0 +1,231 @@
#pragma once
#include "KArcCacheNode.h"
#include <unordered_map>
#include <map>
#include <mutex>
namespace KamaCache
{
template<typename Key, typename Value>
class ArcLfuPart
{
public:
using NodeType = ArcNode<Key, Value>;
using NodePtr = std::shared_ptr<NodeType>;
using NodeMap = std::unordered_map<Key, NodePtr>;
using FreqMap = std::map<size_t, std::list<NodePtr>>;
explicit ArcLfuPart(size_t capacity, size_t transformThreshold)
: capacity_(capacity)
, ghostCapacity_(capacity)
, transformThreshold_(transformThreshold)
, minFreq_(0)
{
initializeLists();
}
bool put(Key key, Value value)
{
if (capacity_ == 0)
return false;
std::lock_guard<std::mutex> lock(mutex_);
auto it = mainCache_.find(key);
if (it != mainCache_.end())
{
return updateExistingNode(it->second, value);
}
return addNewNode(key, value);
}
bool get(Key key, Value& value)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = mainCache_.find(key);
if (it != mainCache_.end())
{
updateNodeFrequency(it->second);
value = it->second->getValue();
return true;
}
return false;
}
bool contain(Key key)
{
return mainCache_.find(key) != mainCache_.end();
}
bool checkGhost(Key key)
{
auto it = ghostCache_.find(key);
if (it != ghostCache_.end())
{
removeFromGhost(it->second);
ghostCache_.erase(it);
return true;
}
return false;
}
void increaseCapacity() { ++capacity_; }
bool decreaseCapacity()
{
if (capacity_ <= 0) return false;
if (mainCache_.size() == capacity_)
{
evictLeastFrequent();
}
--capacity_;
return true;
}
private:
void initializeLists()
{
ghostHead_ = std::make_shared<NodeType>();
ghostTail_ = std::make_shared<NodeType>();
ghostHead_->next_ = ghostTail_;
ghostTail_->prev_ = ghostHead_;
}
bool updateExistingNode(NodePtr node, const Value& value)
{
node->setValue(value);
updateNodeFrequency(node);
return true;
}
bool addNewNode(const Key& key, const Value& value)
{
if (mainCache_.size() >= capacity_)
{
evictLeastFrequent();
}
NodePtr newNode = std::make_shared<NodeType>(key, value);
mainCache_[key] = newNode;
// 将新节点添加到频率为1的列表中
if (freqMap_.find(1) == freqMap_.end())
{
freqMap_[1] = std::list<NodePtr>();
}
freqMap_[1].push_back(newNode);
minFreq_ = 1;
return true;
}
void updateNodeFrequency(NodePtr node)
{
size_t oldFreq = node->getAccessCount();
node->incrementAccessCount();
size_t newFreq = node->getAccessCount();
// 从旧频率列表中移除
auto& oldList = freqMap_[oldFreq];
oldList.remove(node);
if (oldList.empty())
{
freqMap_.erase(oldFreq);
if (oldFreq == minFreq_)
{
minFreq_ = newFreq;
}
}
// 添加到新频率列表
if (freqMap_.find(newFreq) == freqMap_.end())
{
freqMap_[newFreq] = std::list<NodePtr>();
}
freqMap_[newFreq].push_back(node);
}
void evictLeastFrequent()
{
if (freqMap_.empty())
return;
// 获取最小频率的列表
auto& minFreqList = freqMap_[minFreq_];
if (minFreqList.empty())
return;
// 移除最少使用的节点
NodePtr leastNode = minFreqList.front();
minFreqList.pop_front();
// 如果该频率的列表为空,则删除该频率项
if (minFreqList.empty())
{
freqMap_.erase(minFreq_);
// 更新最小频率
if (!freqMap_.empty())
{
minFreq_ = freqMap_.begin()->first;
}
}
// 将节点移到幽灵缓存
if (ghostCache_.size() >= ghostCapacity_)
{
removeOldestGhost();
}
addToGhost(leastNode);
// 从主缓存中移除
mainCache_.erase(leastNode->getKey());
}
void removeFromGhost(NodePtr node)
{
if (!node->prev_.expired() && node->next_) {
auto prev = node->prev_.lock();
prev->next_ = node->next_;
node->next_->prev_ = node->prev_;
node->next_ = nullptr; // 清空指针,防止悬垂引用
}
}
void addToGhost(NodePtr node)
{
node->next_ = ghostTail_;
node->prev_ = ghostTail_->prev_;
if (!ghostTail_->prev_.expired()) {
ghostTail_->prev_.lock()->next_ = node;
}
ghostTail_->prev_ = node;
ghostCache_[node->getKey()] = node;
}
void removeOldestGhost()
{
NodePtr oldestGhost = ghostHead_->next_;
if (oldestGhost != ghostTail_)
{
removeFromGhost(oldestGhost);
ghostCache_.erase(oldestGhost->getKey());
}
}
private:
size_t capacity_;
size_t ghostCapacity_;
size_t transformThreshold_;
size_t minFreq_;
std::mutex mutex_;
NodeMap mainCache_;
NodeMap ghostCache_;
FreqMap freqMap_;
NodePtr ghostHead_;
NodePtr ghostTail_;
};
} // namespace KamaCache

222
KArcCache/KArcLruPart.h Normal file
View File

@@ -0,0 +1,222 @@
#pragma once
#include "KArcCacheNode.h"
#include <unordered_map>
#include <mutex>
namespace KamaCache
{
template<typename Key, typename Value>
class ArcLruPart
{
public:
using NodeType = ArcNode<Key, Value>;
using NodePtr = std::shared_ptr<NodeType>;
using NodeMap = std::unordered_map<Key, NodePtr>;
explicit ArcLruPart(size_t capacity, size_t transformThreshold)
: capacity_(capacity)
, ghostCapacity_(capacity)
, transformThreshold_(transformThreshold)
{
initializeLists();
}
bool put(Key key, Value value)
{
if (capacity_ == 0) return false;
std::lock_guard<std::mutex> lock(mutex_);
auto it = mainCache_.find(key);
if (it != mainCache_.end())
{
return updateExistingNode(it->second, value);
}
return addNewNode(key, value);
}
bool get(Key key, Value& value, bool& shouldTransform)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = mainCache_.find(key);
if (it != mainCache_.end())
{
shouldTransform = updateNodeAccess(it->second);
value = it->second->getValue();
return true;
}
return false;
}
bool checkGhost(Key key)
{
auto it = ghostCache_.find(key);
if (it != ghostCache_.end()) {
removeFromGhost(it->second);
ghostCache_.erase(it);
return true;
}
return false;
}
void increaseCapacity() { ++capacity_; }
bool decreaseCapacity()
{
if (capacity_ <= 0) return false;
if (mainCache_.size() == capacity_) {
evictLeastRecent();
}
--capacity_;
return true;
}
private:
void initializeLists()
{
mainHead_ = std::make_shared<NodeType>();
mainTail_ = std::make_shared<NodeType>();
mainHead_->next_ = mainTail_;
mainTail_->prev_ = mainHead_;
ghostHead_ = std::make_shared<NodeType>();
ghostTail_ = std::make_shared<NodeType>();
ghostHead_->next_ = ghostTail_;
ghostTail_->prev_ = ghostHead_;
}
bool updateExistingNode(NodePtr node, const Value& value)
{
node->setValue(value);
moveToFront(node);
return true;
}
bool addNewNode(const Key& key, const Value& value)
{
if (mainCache_.size() >= capacity_)
{
evictLeastRecent(); // 驱逐最近最少访问
}
NodePtr newNode = std::make_shared<NodeType>(key, value);
mainCache_[key] = newNode;
addToFront(newNode);
return true;
}
bool updateNodeAccess(NodePtr node)
{
moveToFront(node);
node->incrementAccessCount();
return node->getAccessCount() >= transformThreshold_;
}
void moveToFront(NodePtr node)
{
// 先从当前位置移除
if (!node->prev_.expired() && node->next_) {
auto prev = node->prev_.lock();
prev->next_ = node->next_;
node->next_->prev_ = node->prev_;
node->next_ = nullptr; // 清空指针,防止悬垂引用
}
// 添加到头部
addToFront(node);
}
void addToFront(NodePtr node)
{
node->next_ = mainHead_->next_;
node->prev_ = mainHead_;
mainHead_->next_->prev_ = node;
mainHead_->next_ = node;
}
void evictLeastRecent()
{
NodePtr leastRecent = mainTail_->prev_.lock();
if (!leastRecent || leastRecent == mainHead_)
return;
// 从主链表中移除
removeFromMain(leastRecent);
// 添加到幽灵缓存
if (ghostCache_.size() >= ghostCapacity_)
{
removeOldestGhost();
}
addToGhost(leastRecent);
// 从主缓存映射中移除
mainCache_.erase(leastRecent->getKey());
}
void removeFromMain(NodePtr node)
{
if (!node->prev_.expired() && node->next_) {
auto prev = node->prev_.lock();
prev->next_ = node->next_;
node->next_->prev_ = node->prev_;
node->next_ = nullptr; // 清空指针,防止悬垂引用
}
}
void removeFromGhost(NodePtr node)
{
if (!node->prev_.expired() && node->next_) {
auto prev = node->prev_.lock();
prev->next_ = node->next_;
node->next_->prev_ = node->prev_;
node->next_ = nullptr; // 清空指针,防止悬垂引用
}
}
void addToGhost(NodePtr node)
{
// 重置节点的访问计数
node->accessCount_ = 1;
// 添加到幽灵缓存的头部
node->next_ = ghostHead_->next_;
node->prev_ = ghostHead_;
ghostHead_->next_->prev_ = node;
ghostHead_->next_ = node;
// 添加到幽灵缓存映射
ghostCache_[node->getKey()] = node;
}
void removeOldestGhost()
{
// 使用lock()方法并添加null检查
NodePtr oldestGhost = ghostTail_->prev_.lock();
if (!oldestGhost || oldestGhost == ghostHead_)
return;
removeFromGhost(oldestGhost);
ghostCache_.erase(oldestGhost->getKey());
}
private:
size_t capacity_;
size_t ghostCapacity_;
size_t transformThreshold_; // 转换门槛值
std::mutex mutex_;
NodeMap mainCache_; // key -> ArcNode
NodeMap ghostCache_;
// 主链表
NodePtr mainHead_;
NodePtr mainTail_;
// 淘汰链表
NodePtr ghostHead_;
NodePtr ghostTail_;
};
} // namespace KamaCache

22
KICachePolicy.h Normal file
View File

@@ -0,0 +1,22 @@
#pragma once
namespace KamaCache
{
template <typename Key, typename Value>
class KICachePolicy
{
public:
virtual ~KICachePolicy() {};
// 添加缓存接口
virtual void put(Key key, Value value) = 0;
// key是传入参数 访问到的值以传出参数的形式返回 | 访问成功返回true
virtual bool get(Key key, Value& value) = 0;
// 如果缓存中能找到key则直接返回value
virtual Value get(Key key) = 0;
};
} // namespace KamaCache

379
KLfuCache.h Normal file
View File

@@ -0,0 +1,379 @@
#pragma once
#include <cmath>
#include <memory>
#include <mutex>
#include <thread>
#include <unordered_map>
#include <vector>
#include "KICachePolicy.h"
namespace KamaCache
{
template<typename Key, typename Value> class KLfuCache;
template<typename Key, typename Value>
class FreqList
{
private:
struct Node
{
int freq; // 访问频次
Key key;
Value value;
std::weak_ptr<Node> pre; // 上一结点改为weak_ptr打破循环引用
std::shared_ptr<Node> next;
Node()
: freq(1), next(nullptr) {}
Node(Key key, Value value)
: freq(1), key(key), value(value), next(nullptr) {}
};
using NodePtr = std::shared_ptr<Node>;
int freq_; // 访问频率
NodePtr head_; // 假头结点
NodePtr tail_; // 假尾结点
public:
explicit FreqList(int n)
: freq_(n)
{
head_ = std::make_shared<Node>();
tail_ = std::make_shared<Node>();
head_->next = tail_;
tail_->pre = head_;
}
bool isEmpty() const
{
return head_->next == tail_;
}
// 提那家结点管理方法
void addNode(NodePtr node)
{
if (!node || !head_ || !tail_)
return;
node->pre = tail_->pre;
node->next = tail_;
tail_->pre.lock()->next = node; // 使用lock()获取shared_ptr
tail_->pre = node;
}
void removeNode(NodePtr node)
{
if (!node || !head_ || !tail_)
return;
if (node->pre.expired() || !node->next)
return;
auto pre = node->pre.lock(); // 使用lock()获取shared_ptr
pre->next = node->next;
node->next->pre = pre;
node->next = nullptr; // 确保显式置空next指针彻底断开节点与链表的连接
}
NodePtr getFirstNode() const { return head_->next; }
friend class KLfuCache<Key, Value>;
};
template <typename Key, typename Value>
class KLfuCache : public KICachePolicy<Key, Value>
{
public:
using Node = typename FreqList<Key, Value>::Node;
using NodePtr = std::shared_ptr<Node>;
using NodeMap = std::unordered_map<Key, NodePtr>;
KLfuCache(int capacity, int maxAverageNum = 1000000)
: capacity_(capacity), minFreq_(INT8_MAX), maxAverageNum_(maxAverageNum),
curAverageNum_(0), curTotalNum_(0)
{}
~KLfuCache() override = default;
void put(Key key, Value value) override
{
if (capacity_ == 0)
return;
std::lock_guard<std::mutex> lock(mutex_);
auto it = nodeMap_.find(key);
if (it != nodeMap_.end())
{
// 重置其value值
it->second->value = value;
// 找到了直接调整就好了不用再去get中再找一遍但其实影响不大
getInternal(it->second, value);
return;
}
putInternal(key, value);
}
// value值为传出参数
bool get(Key key, Value& value) override
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = nodeMap_.find(key);
if (it != nodeMap_.end())
{
getInternal(it->second, value);
return true;
}
return false;
}
Value get(Key key) override
{
Value value;
get(key, value);
return value;
}
// 清空缓存,回收资源
void purge()
{
nodeMap_.clear();
freqToFreqList_.clear();
}
private:
void putInternal(Key key, Value value); // 添加缓存
void getInternal(NodePtr node, Value& value); // 获取缓存
void kickOut(); // 移除缓存中的过期数据
void removeFromFreqList(NodePtr node); // 从频率列表中移除节点
void addToFreqList(NodePtr node); // 添加到频率列表
void addFreqNum(); // 增加平均访问等频率
void decreaseFreqNum(int num); // 减少平均访问等频率
void handleOverMaxAverageNum(); // 处理当前平均访问频率超过上限的情况
void updateMinFreq();
private:
int capacity_; // 缓存容量
int minFreq_; // 最小访问频次(用于找到最小访问频次结点)
int maxAverageNum_; // 最大平均访问频次
int curAverageNum_; // 当前平均访问频次
int curTotalNum_; // 当前访问所有缓存次数总数
std::mutex mutex_; // 互斥锁
NodeMap nodeMap_; // key 到 缓存节点的映射
std::unordered_map<int, FreqList<Key, Value>*> freqToFreqList_;// 访问频次到该频次链表的映射
};
template<typename Key, typename Value>
void KLfuCache<Key, Value>::getInternal(NodePtr node, Value& value)
{
// 找到之后需要将其从低访问频次的链表中删除,并且添加到+1的访问频次链表中
// 访问频次+1, 然后把value值返回
value = node->value;
// 从原有访问频次的链表中删除节点
removeFromFreqList(node);
node->freq++;
addToFreqList(node);
// 如果当前node的访问频次如果等于minFreq+1并且其前驱链表为空则说明
// freqToFreqList_[node->freq - 1]链表因node的迁移已经空了需要更新最小访问频次
if (node->freq - 1 == minFreq_ && freqToFreqList_[node->freq - 1]->isEmpty())
minFreq_++;
// 总访问频次和当前平均访问频次都随之增加
addFreqNum();
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::putInternal(Key key, Value value)
{
// 如果不在缓存中,则需要判断缓存是否已满
if (nodeMap_.size() == capacity_)
{
// 缓存已满,删除最不常访问的结点,更新当前平均访问频次和总访问频次
kickOut();
}
// 创建新结点,将新结点添加进入,更新最小访问频次
NodePtr node = std::make_shared<Node>(key, value);
nodeMap_[key] = node;
addToFreqList(node);
addFreqNum();
minFreq_ = std::min(minFreq_, 1);
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::kickOut()
{
NodePtr node = freqToFreqList_[minFreq_]->getFirstNode();
removeFromFreqList(node);
nodeMap_.erase(node->key);
decreaseFreqNum(node->freq);
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::removeFromFreqList(NodePtr node)
{
// 检查结点是否为空
if (!node)
return;
auto freq = node->freq;
freqToFreqList_[freq]->removeNode(node);
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::addToFreqList(NodePtr node)
{
// 检查结点是否为空
if (!node)
return;
// 添加进入相应的频次链表前需要判断该频次链表是否存在
auto freq = node->freq;
if (freqToFreqList_.find(node->freq) == freqToFreqList_.end())
{
// 不存在则创建
freqToFreqList_[node->freq] = new FreqList<Key, Value>(node->freq);
}
freqToFreqList_[freq]->addNode(node);
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::addFreqNum()
{
curTotalNum_++;
if (nodeMap_.empty())
curAverageNum_ = 0;
else
curAverageNum_ = curTotalNum_ / nodeMap_.size();
if (curAverageNum_ > maxAverageNum_)
{
handleOverMaxAverageNum();
}
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::decreaseFreqNum(int num)
{
// 减少平均访问频次和总访问频次
curTotalNum_ -= num;
if (nodeMap_.empty())
curAverageNum_ = 0;
else
curAverageNum_ = curTotalNum_ / nodeMap_.size();
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::handleOverMaxAverageNum()
{
if (nodeMap_.empty())
return;
// 当前平均访问频次已经超过了最大平均访问频次,所有结点的访问频次- (maxAverageNum_ / 2)
for (auto it = nodeMap_.begin(); it != nodeMap_.end(); ++it)
{
// 检查结点是否为空
if (!it->second)
continue;
NodePtr node = it->second;
// 先从当前频率列表中移除
removeFromFreqList(node);
// 减少频率
node->freq -= maxAverageNum_ / 2;
if (node->freq < 1) node->freq = 1;
// 添加到新的频率列表
addToFreqList(node);
}
// 更新最小频率
updateMinFreq();
}
template<typename Key, typename Value>
void KLfuCache<Key, Value>::updateMinFreq()
{
minFreq_ = INT8_MAX;
for (const auto& pair : freqToFreqList_)
{
if (pair.second && !pair.second->isEmpty())
{
minFreq_ = std::min(minFreq_, pair.first);
}
}
if (minFreq_ == INT8_MAX)
minFreq_ = 1;
}
// 并没有牺牲空间换时间,他是把原有缓存大小进行了分片。
template<typename Key, typename Value>
class KHashLfuCache
{
public:
KHashLfuCache(size_t capacity, int sliceNum, int maxAverageNum = 10)
: sliceNum_(sliceNum > 0 ? sliceNum : std::thread::hardware_concurrency())
, capacity_(capacity)
{
size_t sliceSize = std::ceil(capacity_ / static_cast<double>(sliceNum_)); // 每个lfu分片的容量
for (int i = 0; i < sliceNum_; ++i)
{
lfuSliceCaches_.emplace_back(new KLfuCache<Key, Value>(sliceSize, maxAverageNum));
}
}
void put(Key key, Value value)
{
// 根据key找出对应的lfu分片
size_t sliceIndex = Hash(key) % sliceNum_;
lfuSliceCaches_[sliceIndex]->put(key, value);
}
bool get(Key key, Value& value)
{
// 根据key找出对应的lfu分片
size_t sliceIndex = Hash(key) % sliceNum_;
return lfuSliceCaches_[sliceIndex]->get(key, value);
}
Value get(Key key)
{
Value value;
get(key, value);
return value;
}
// 清除缓存
void purge()
{
for (auto& lfuSliceCache : lfuSliceCaches_)
{
lfuSliceCache->purge();
}
}
private:
// 将key计算成对应哈希值
size_t Hash(Key key)
{
std::hash<Key> hashFunc;
return hashFunc(key);
}
private:
size_t capacity_; // 缓存总容量
int sliceNum_; // 缓存分片数量
std::vector<std::unique_ptr<KLfuCache<Key, Value>>> lfuSliceCaches_; // 缓存lfu分片容器
};
} // namespace KamaCache

326
KLruCache.h Normal file
View File

@@ -0,0 +1,326 @@
#pragma once
#include <cstring>
#include <list>
#include <memory>
#include <mutex>
#include <unordered_map>
#include "KICachePolicy.h"
namespace KamaCache
{
// 前向声明
template<typename Key, typename Value> class KLruCache;
template<typename Key, typename Value>
class LruNode
{
private:
Key key_;
Value value_;
size_t accessCount_; // 访问次数
std::weak_ptr<LruNode<Key, Value>> prev_; // 改为weak_ptr打破循环引用
std::shared_ptr<LruNode<Key, Value>> next_;
public:
LruNode(Key key, Value value)
: key_(key)
, value_(value)
, accessCount_(1)
{}
// 提供必要的访问器
Key getKey() const { return key_; }
Value getValue() const { return value_; }
void setValue(const Value& value) { value_ = value; }
size_t getAccessCount() const { return accessCount_; }
void incrementAccessCount() { ++accessCount_; }
friend class KLruCache<Key, Value>;
};
template<typename Key, typename Value>
class KLruCache : public KICachePolicy<Key, Value>
{
public:
using LruNodeType = LruNode<Key, Value>;
using NodePtr = std::shared_ptr<LruNodeType>;
using NodeMap = std::unordered_map<Key, NodePtr>;
KLruCache(int capacity)
: capacity_(capacity)
{
initializeList();
}
~KLruCache() override = default;
// 添加缓存
void put(Key key, Value value) override
{
if (capacity_ <= 0)
return;
std::lock_guard<std::mutex> lock(mutex_);
auto it = nodeMap_.find(key);
if (it != nodeMap_.end())
{
// 如果在当前容器中,则更新value,并调用get方法代表该数据刚被访问
updateExistingNode(it->second, value);
return ;
}
addNewNode(key, value);
}
bool get(Key key, Value& value) override
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = nodeMap_.find(key);
if (it != nodeMap_.end())
{
moveToMostRecent(it->second);
value = it->second->getValue();
return true;
}
return false;
}
Value get(Key key) override
{
Value value{};
// memset(&value, 0, sizeof(value)); // memset 是按字节设置内存的,对于复杂类型(如 string使用 memset 可能会破坏对象的内部结构
get(key, value);
return value;
}
// 删除指定元素
void remove(Key key)
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = nodeMap_.find(key);
if (it != nodeMap_.end())
{
removeNode(it->second);
nodeMap_.erase(it);
}
}
private:
void initializeList()
{
// 创建首尾虚拟节点
dummyHead_ = std::make_shared<LruNodeType>(Key(), Value());
dummyTail_ = std::make_shared<LruNodeType>(Key(), Value());
dummyHead_->next_ = dummyTail_;
dummyTail_->prev_ = dummyHead_;
}
void updateExistingNode(NodePtr node, const Value& value)
{
node->setValue(value);
moveToMostRecent(node);
}
void addNewNode(const Key& key, const Value& value)
{
if (nodeMap_.size() >= capacity_)
{
evictLeastRecent();
}
NodePtr newNode = std::make_shared<LruNodeType>(key, value);
insertNode(newNode);
nodeMap_[key] = newNode;
}
// 将该节点移动到最新的位置
void moveToMostRecent(NodePtr node)
{
removeNode(node);
insertNode(node);
}
void removeNode(NodePtr node)
{
if(!node->prev_.expired() && node->next_)
{
auto prev = node->prev_.lock(); // 使用lock()获取shared_ptr
prev->next_ = node->next_;
node->next_->prev_ = prev;
node->next_ = nullptr; // 清空next_指针彻底断开节点与链表的连接
}
}
// 从尾部插入结点
void insertNode(NodePtr node)
{
node->next_ = dummyTail_;
node->prev_ = dummyTail_->prev_;
dummyTail_->prev_.lock()->next_ = node; // 使用lock()获取shared_ptr
dummyTail_->prev_ = node;
}
// 驱逐最近最少访问
void evictLeastRecent()
{
NodePtr leastRecent = dummyHead_->next_;
removeNode(leastRecent);
nodeMap_.erase(leastRecent->getKey());
}
private:
int capacity_; // 缓存容量
NodeMap nodeMap_; // key -> Node
std::mutex mutex_;
NodePtr dummyHead_; // 虚拟头结点
NodePtr dummyTail_;
};
// LRU优化Lru-k版本。 通过继承的方式进行再优化
template<typename Key, typename Value>
class KLruKCache : public KLruCache<Key, Value>
{
public:
KLruKCache(int capacity, int historyCapacity, int k)
: KLruCache<Key, Value>(capacity) // 调用基类构造
, historyList_(std::make_unique<KLruCache<Key, size_t>>(historyCapacity))
, k_(k)
{}
Value get(Key key)
{
// 首先尝试从主缓存获取数据
Value value{};
bool inMainCache = KLruCache<Key, Value>::get(key, value);
// 获取并更新访问历史计数
size_t historyCount = historyList_->get(key);
historyCount++;
historyList_->put(key, historyCount);
// 如果数据在主缓存中,直接返回
if (inMainCache)
{
return value;
}
// 如果数据不在主缓存但访问次数达到了k次
if (historyCount >= k_)
{
// 检查是否有历史值记录
auto it = historyValueMap_.find(key);
if (it != historyValueMap_.end())
{
// 有历史值,将其添加到主缓存
Value storedValue = it->second;
// 从历史记录移除
historyList_->remove(key);
historyValueMap_.erase(it);
// 添加到主缓存
KLruCache<Key, Value>::put(key, storedValue);
return storedValue;
}
// 没有历史值记录,无法添加到缓存,返回默认值
}
// 数据不在主缓存且不满足添加条件,返回默认值
return value;
}
void put(Key key, Value value)
{
// 检查是否已在主缓存
Value existingValue{};
bool inMainCache = KLruCache<Key, Value>::get(key, existingValue);
if (inMainCache)
{
// 已在主缓存,直接更新
KLruCache<Key, Value>::put(key, value);
return;
}
// 获取并更新访问历史
size_t historyCount = historyList_->get(key);
historyCount++;
historyList_->put(key, historyCount);
// 保存值到历史记录映射供后续get操作使用
historyValueMap_[key] = value;
// 检查是否达到k次访问阈值
if (historyCount >= k_)
{
// 达到阈值,添加到主缓存
historyList_->remove(key);
historyValueMap_.erase(key);
KLruCache<Key, Value>::put(key, value);
}
}
private:
int k_; // 进入缓存队列的评判标准
std::unique_ptr<KLruCache<Key, size_t>> historyList_; // 访问数据历史记录(value为访问次数)
std::unordered_map<Key, Value> historyValueMap_; // 存储未达到k次访问的数据值
};
// lru优化对lru进行分片提高高并发使用的性能
template<typename Key, typename Value>
class KHashLruCaches
{
public:
KHashLruCaches(size_t capacity, int sliceNum)
: capacity_(capacity)
, sliceNum_(sliceNum > 0 ? sliceNum : std::thread::hardware_concurrency())
{
size_t sliceSize = std::ceil(capacity / static_cast<double>(sliceNum_)); // 获取每个分片的大小
for (int i = 0; i < sliceNum_; ++i)
{
lruSliceCaches_.emplace_back(new KLruCache<Key, Value>(sliceSize));
}
}
void put(Key key, Value value)
{
// 获取key的hash值并计算出对应的分片索引
size_t sliceIndex = Hash(key) % sliceNum_;
lruSliceCaches_[sliceIndex]->put(key, value);
}
bool get(Key key, Value& value)
{
// 获取key的hash值并计算出对应的分片索引
size_t sliceIndex = Hash(key) % sliceNum_;
return lruSliceCaches_[sliceIndex]->get(key, value);
}
Value get(Key key)
{
Value value;
memset(&value, 0, sizeof(value));
get(key, value);
return value;
}
private:
// 将key转换为对应hash值
size_t Hash(Key key)
{
std::hash<Key> hashFunc;
return hashFunc(key);
}
private:
size_t capacity_; // 总容量
int sliceNum_; // 切片数量
std::vector<std::unique_ptr<KLruCache<Key, Value>>> lruSliceCaches_; // 切片LRU缓存
};
} // namespace KamaCache

674
LICENSE Normal file
View File

@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.

54
README.md Normal file
View File

@@ -0,0 +1,54 @@
# KamaCache
> ⭐️ 本项目为[【代码随想录知识星球】](https://programmercarl.com/other/kstar.html) 教学项目
> ⭐️ 在 [缓存项目文档](https://www.programmercarl.com/other/project_huancun.html) 里详细讲解:**项目前置知识 + 项目细节 + 代码解读 + 项目难点 + 面试题与回答 + 简历写法 + 项目拓展**。 全面帮助你用这个项目求职面试!
## 项目介绍
本项目使用多个页面替换策略实现一个线程安全的缓存:
- LRU最近最久未使用
- LFU最近不经常使用
- ARC自适应替换
对于LRU和LFU策略我在其基础的缓存策略上进行了相应的优化例如
- LRU优化
- LRU分片对多线程下的高并发访问有性能上的优化
- LRU-k一定程度上防止热点数据被冷数据挤出容器而造成缓存污染等问题
- LFU优化
- LFU分片对多线程下的高并发访问有性能上的优化
- 引入最大平均访问频次:解决过去的热点数据最近一直没被访问,却仍占用缓存等问题
## 系统环境
```
Ubuntu 22.04 LTS
```
## 编译
创建一个build文件夹并进入
```
mkdir build && cd build
```
生成构建文件
```
cmake ..
```
构建项目
```
make
```
如果要清理生成的可执行文件
```
make clean
```
## 运行
```
./main
```
## 测试结果
不同缓存策略缓存命中率测试对比结果如下:
ps: 该测试代码只是尽可能地模拟真实的访问场景,但是跟真实的场景仍存在一定差距,测试结果仅供参考。)
![alt text](images/hitTest.jpg)

BIN
images/hitTest.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 126 KiB

286
testAllCachePolicy.cpp Normal file
View File

@@ -0,0 +1,286 @@
#include <iostream>
#include <string>
#include <chrono>
#include <vector>
#include <iomanip>
#include <random>
#include <algorithm>
#include <array>
#include "KICachePolicy.h"
#include "KLfuCache.h"
#include "KLruCache.h"
#include "KArcCache/KArcCache.h"
class Timer {
public:
Timer() : start_(std::chrono::high_resolution_clock::now()) {}
double elapsed() {
auto now = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::milliseconds>(now - start_).count();
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start_;
};
// 辅助函数:打印结果
void printResults(const std::string& testName, int capacity,
const std::vector<int>& get_operations,
const std::vector<int>& hits) {
std::cout << "=== " << testName << " 结果汇总 ===" << std::endl;
std::cout << "缓存大小: " << capacity << std::endl;
// 假设对应的算法名称已在测试函数中定义
std::vector<std::string> names;
if (hits.size() == 3) {
names = {"LRU", "LFU", "ARC"};
} else if (hits.size() == 4) {
names = {"LRU", "LFU", "ARC", "LRU-K"};
} else if (hits.size() == 5) {
names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"};
}
for (size_t i = 0; i < hits.size(); ++i) {
double hitRate = 100.0 * hits[i] / get_operations[i];
std::cout << (i < names.size() ? names[i] : "Algorithm " + std::to_string(i+1))
<< " - 命中率: " << std::fixed << std::setprecision(2)
<< hitRate << "% ";
// 添加具体命中次数和总操作次数
std::cout << "(" << hits[i] << "/" << get_operations[i] << ")" << std::endl;
}
std::cout << std::endl; // 添加空行,使输出更清晰
}
void testHotDataAccess() {
std::cout << "\n=== 测试场景1热点数据访问测试 ===" << std::endl;
const int CAPACITY = 20; // 缓存容量
const int OPERATIONS = 500000; // 总操作次数
const int HOT_KEYS = 20; // 热点数据数量
const int COLD_KEYS = 5000; // 冷数据数量
KamaCache::KLruCache<int, std::string> lru(CAPACITY);
KamaCache::KLfuCache<int, std::string> lfu(CAPACITY);
KamaCache::KArcCache<int, std::string> arc(CAPACITY);
// 为LRU-K设置合适的参数
// - 主缓存容量与其他算法相同
// - 历史记录容量设为可能访问的所有键数量
// - k=2表示数据被访问2次后才会进入缓存适合区分热点和冷数据
KamaCache::KLruKCache<int, std::string> lruk(CAPACITY, HOT_KEYS + COLD_KEYS, 2);
KamaCache::KLfuCache<int, std::string> lfuAging(CAPACITY, 20000);
std::random_device rd;
std::mt19937 gen(rd());
// 基类指针指向派生类对象添加LFU-Aging
std::array<KamaCache::KICachePolicy<int, std::string>*, 5> caches = {&lru, &lfu, &arc, &lruk, &lfuAging};
std::vector<int> hits(5, 0);
std::vector<int> get_operations(5, 0);
std::vector<std::string> names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"};
// 为所有的缓存对象进行相同的操作序列测试
for (int i = 0; i < caches.size(); ++i) {
// 先预热缓存,插入一些数据
for (int key = 0; key < HOT_KEYS; ++key) {
std::string value = "value" + std::to_string(key);
caches[i]->put(key, value);
}
// 交替进行put和get操作模拟真实场景
for (int op = 0; op < OPERATIONS; ++op) {
// 大多数缓存系统中读操作比写操作频繁
// 所以设置30%概率进行写操作
bool isPut = (gen() % 100 < 30);
int key;
// 70%概率访问热点数据30%概率访问冷数据
if (gen() % 100 < 70) {
key = gen() % HOT_KEYS; // 热点数据
} else {
key = HOT_KEYS + (gen() % COLD_KEYS); // 冷数据
}
if (isPut) {
// 执行put操作
std::string value = "value" + std::to_string(key) + "_v" + std::to_string(op % 100);
caches[i]->put(key, value);
} else {
// 执行get操作并记录命中情况
std::string result;
get_operations[i]++;
if (caches[i]->get(key, result)) {
hits[i]++;
}
}
}
}
// 打印测试结果
printResults("热点数据访问测试", CAPACITY, get_operations, hits);
}
void testLoopPattern() {
std::cout << "\n=== 测试场景2循环扫描测试 ===" << std::endl;
const int CAPACITY = 50; // 缓存容量
const int LOOP_SIZE = 500; // 循环范围大小
const int OPERATIONS = 200000; // 总操作次数
KamaCache::KLruCache<int, std::string> lru(CAPACITY);
KamaCache::KLfuCache<int, std::string> lfu(CAPACITY);
KamaCache::KArcCache<int, std::string> arc(CAPACITY);
// 为LRU-K设置合适的参数
// - 历史记录容量设为总循环大小的两倍,覆盖范围内和范围外的数据
// - k=2对于循环访问这是一个合理的阈值
KamaCache::KLruKCache<int, std::string> lruk(CAPACITY, LOOP_SIZE * 2, 2);
KamaCache::KLfuCache<int, std::string> lfuAging(CAPACITY, 3000);
std::array<KamaCache::KICachePolicy<int, std::string>*, 5> caches = {&lru, &lfu, &arc, &lruk, &lfuAging};
std::vector<int> hits(5, 0);
std::vector<int> get_operations(5, 0);
std::vector<std::string> names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"};
std::random_device rd;
std::mt19937 gen(rd());
// 为每种缓存算法运行相同的测试
for (int i = 0; i < caches.size(); ++i) {
// 先预热一部分数据只加载20%的数据)
for (int key = 0; key < LOOP_SIZE / 5; ++key) {
std::string value = "loop" + std::to_string(key);
caches[i]->put(key, value);
}
// 设置循环扫描的当前位置
int current_pos = 0;
// 交替进行读写操作,模拟真实场景
for (int op = 0; op < OPERATIONS; ++op) {
// 20%概率是写操作80%概率是读操作
bool isPut = (gen() % 100 < 20);
int key;
// 按照不同模式选择键
if (op % 100 < 60) { // 60%顺序扫描
key = current_pos;
current_pos = (current_pos + 1) % LOOP_SIZE;
} else if (op % 100 < 90) { // 30%随机跳跃
key = gen() % LOOP_SIZE;
} else { // 10%访问范围外数据
key = LOOP_SIZE + (gen() % LOOP_SIZE);
}
if (isPut) {
// 执行put操作更新数据
std::string value = "loop" + std::to_string(key) + "_v" + std::to_string(op % 100);
caches[i]->put(key, value);
} else {
// 执行get操作并记录命中情况
std::string result;
get_operations[i]++;
if (caches[i]->get(key, result)) {
hits[i]++;
}
}
}
}
printResults("循环扫描测试", CAPACITY, get_operations, hits);
}
void testWorkloadShift() {
std::cout << "\n=== 测试场景3工作负载剧烈变化测试 ===" << std::endl;
const int CAPACITY = 30; // 缓存容量
const int OPERATIONS = 80000; // 总操作次数
const int PHASE_LENGTH = OPERATIONS / 5; // 每个阶段的长度
KamaCache::KLruCache<int, std::string> lru(CAPACITY);
KamaCache::KLfuCache<int, std::string> lfu(CAPACITY);
KamaCache::KArcCache<int, std::string> arc(CAPACITY);
KamaCache::KLruKCache<int, std::string> lruk(CAPACITY, 500, 2);
KamaCache::KLfuCache<int, std::string> lfuAging(CAPACITY, 10000);
std::random_device rd;
std::mt19937 gen(rd());
std::array<KamaCache::KICachePolicy<int, std::string>*, 5> caches = {&lru, &lfu, &arc, &lruk, &lfuAging};
std::vector<int> hits(5, 0);
std::vector<int> get_operations(5, 0);
std::vector<std::string> names = {"LRU", "LFU", "ARC", "LRU-K", "LFU-Aging"};
// 为每种缓存算法运行相同的测试
for (int i = 0; i < caches.size(); ++i) {
// 先预热缓存,只插入少量初始数据
for (int key = 0; key < 30; ++key) {
std::string value = "init" + std::to_string(key);
caches[i]->put(key, value);
}
// 进行多阶段测试,每个阶段有不同的访问模式
for (int op = 0; op < OPERATIONS; ++op) {
// 确定当前阶段
int phase = op / PHASE_LENGTH;
// 每个阶段的读写比例不同
int putProbability;
switch (phase) {
case 0: putProbability = 15; break; // 阶段1: 热点访问15%写入更合理
case 1: putProbability = 30; break; // 阶段2: 大范围随机写比例为30%
case 2: putProbability = 10; break; // 阶段3: 顺序扫描10%写入保持不变
case 3: putProbability = 25; break; // 阶段4: 局部性随机微调为25%
case 4: putProbability = 20; break; // 阶段5: 混合访问调整为20%
default: putProbability = 20;
}
// 确定是读还是写操作
bool isPut = (gen() % 100 < putProbability);
// 根据不同阶段选择不同的访问模式生成key - 优化后的访问范围
int key;
if (op < PHASE_LENGTH) { // 阶段1: 热点访问 - 热点数量5使热点更集中
key = gen() % 5;
} else if (op < PHASE_LENGTH * 2) { // 阶段2: 大范围随机 - 范围400更适合30大小的缓存
key = gen() % 400;
} else if (op < PHASE_LENGTH * 3) { // 阶段3: 顺序扫描 - 保持100个键
key = (op - PHASE_LENGTH * 2) % 100;
} else if (op < PHASE_LENGTH * 4) { // 阶段4: 局部性随机 - 优化局部性区域大小
// 产生5个局部区域每个区域大小为15个键与缓存大小20接近但略小
int locality = (op / 800) % 5; // 调整为5个局部区域
key = locality * 15 + (gen() % 15); // 每区域15个键
} else { // 阶段5: 混合访问 - 增加热点访问比例
int r = gen() % 100;
if (r < 40) { // 40%概率访问热点从30%增加)
key = gen() % 5; // 5个热点键
} else if (r < 70) { // 30%概率访问中等范围
key = 5 + (gen() % 45); // 缩小中等范围为50个键
} else { // 30%概率访问大范围从40%减少)
key = 50 + (gen() % 350); // 大范围也相应缩小
}
}
if (isPut) {
// 执行写操作
std::string value = "value" + std::to_string(key) + "_p" + std::to_string(phase);
caches[i]->put(key, value);
} else {
// 执行读操作并记录命中情况
std::string result;
get_operations[i]++;
if (caches[i]->get(key, result)) {
hits[i]++;
}
}
}
}
printResults("工作负载剧烈变化测试", CAPACITY, get_operations, hits);
}
int main() {
testHotDataAccess();
testLoopPattern();
testWorkloadShift();
return 0;
}