1#ifndef NEFORCE_CORE_CONTAINER_TTL_CACHE_HPP__
2#define NEFORCE_CORE_CONTAINER_TTL_CACHE_HPP__
18NEFORCE_BEGIN_NAMESPACE__
44template <
typename Key,
typename Value>
74 lru_cache<Key, entry> cache_;
75 duration default_ttl_;
77 atomic<bool> running_{
false};
78 refresh_policy refresh_policy_{refresh_policy::never};
79 duration cleanup_interval_{
seconds(1)};
80 thread cleanup_thread_;
81 mutable mutex cv_mutex_;
82 condition_variable cv_;
94 default_ttl_(default_ttl) {}
115 cleanup_interval_ = interval;
117 cleanup_thread_ =
thread([
this] {
137 if (cleanup_thread_.joinable()) {
138 cleanup_thread_.join();
157 void put(
const Key& key,
const Value& value) {
159 cache_.put(key, entry{value, expiry});
172 cache_.put(key, entry{value, expiry});
183 auto opt_entry = cache_.get(key);
188 const entry& e = *opt_entry;
195 entry updated_entry = e;
196 updated_entry.expiry =
clock::now() + default_ttl_;
197 cache_.put(key, updated_entry);
211 auto opt_entry = cache_.peek(key);
215 const entry& e = *opt_entry;
228 bool erase(
const Key& key) {
return cache_.erase(key); }
255 cache_.remove_if([now](
const auto&
pair) {
return pair.
second.expiry < now; });
261NEFORCE_END_NAMESPACE__
size_type size() const noexcept
获取当前缓存大小
clock::duration duration
持续时间类型
ttl_cache(size_type capacity, duration default_ttl=seconds(60))
构造函数
void put(const Key &key, const Value &value)
插入缓存项(使用默认TTL)
size_type capacity() const noexcept
获取缓存容量
void enable_cleanup(duration interval=seconds(1))
启用后台清理线程
void put(const Key &key, const Value &value, duration ttl)
插入缓存项(指定TTL)
void set_refresh_policy(refresh_policy policy)
设置刷新策略
void disable_cleanup()
禁用后台清理线程
@ on_access
访问时刷新,每次访问都重置过期时间
@ sliding_window
滑动窗口,每次访问延长TTL
bool erase(const Key &key)
删除缓存项
clock::time_point time_point
时间点类型
optional< Value > get(const Key &key)
获取缓存项
bool contains(const Key &key)
检查缓存是否包含指定键
unsigned char uint8_t
8位无符号整数类型
duration< int64_t > seconds
秒持续时间
constexpr none_t none
默认空表示
static time_point now() noexcept
获取当前时间点
_NEFORCE time_point< steady_clock > time_point
时间点类型
nanoseconds duration
持续时间类型