Files
seadisk/include/seafile/cache/cache.hpp
T
2026-07-13 23:53:11 +08:00

113 lines
2.8 KiB
C++

//
// Created by Shell on 2026/7/13.
//
#ifndef SEADISK_CACHE_HPP
#define SEADISK_CACHE_HPP
#include <chrono>
#include <shared_mutex>
#include <unordered_map>
namespace seafile::cache {
template<typename K, typename V>
class Cache final{
public:
using Clock = std::chrono::steady_clock;
using Duration = Clock::duration;
/// 设置缓存
/// @param key 键
/// @param value 值
/// @param ttl 超时时间
void put(const K &key, V value, const Duration ttl) {
std::unique_lock lock(mutex_);
cache_[key] = Entry{
std::move(value),
Clock::now() + ttl
};
}
/// 获取缓存值
/// @param key 键
/// @return 缓存值
std::optional<V> get(const K &key) {
// 第一阶段:读锁
{
std::shared_lock lock(mutex_);
auto it = cache_.find(key);
if (it == cache_.end())
return std::nullopt;
if (Clock::now() < it->second.expire_time)
return it->second.value;
}
// 第二阶段:删除过期数据
{
std::unique_lock lock(mutex_);
auto it = cache_.find(key);
if (it != cache_.end() &&
Clock::now() >= it->second.expire_time)
{
cache_.erase(it);
}
}
return std::nullopt;
}
/// 移除缓存
/// @param key 键
void remove(const K &key) {
std::unique_lock lock(mutex_);
cache_.erase(key);
}
///清空缓存
void clear() {
std::unique_lock lock(mutex_);
cache_.clear();
}
///清理过时的缓存
void cleanup() {
auto now = Clock::now();
std::unique_lock lock(mutex_);
for (auto it = cache_.begin(); it != cache_.end();)
{
if (it->second.expireTime <= now)
{
it = cache_.erase(it);
}
else
{
++it;
}
}
}
///缓存大小
size_t size() const {
std::unique_lock lock(mutex_);
return cache_.size();
}
private:
struct Entry final {
V value;
Clock::time_point expire_time;
};
mutable std::shared_mutex mutex_;
std::unordered_map<K, Entry> cache_;
};
}
#endif //SEADISK_CACHE_HPP