1#ifndef NEFORCE_CORE_CONTAINER_TTL_CACHE_HPP__
2#define NEFORCE_CORE_CONTAINER_TTL_CACHE_HPP__
17NEFORCE_BEGIN_NAMESPACE__
43template <
typename Key,
typename Value>
73 lru_cache<Key, entry> cache_;
76 atomic<bool> running_{
false};
79 thread cleanup_thread_;
91 default_ttl_(default_ttl) {}
112 cleanup_interval_ = interval;
114 cleanup_thread_ =
thread([
this] {
116 this_thread::sleep_for(cleanup_interval_);
130 if (cleanup_thread_.joinable()) {
131 cleanup_thread_.join();
150 void put(
const Key& key,
const Value& value) {
152 cache_.put(key, entry{value, expiry});
165 cache_.put(key, entry{value, expiry});
176 auto opt_entry = cache_.get(key);
181 const entry& e = *opt_entry;
188 entry updated_entry = e;
189 updated_entry.expiry =
clock::now() + default_ttl_;
190 cache_.put(key, updated_entry);
204 auto opt_entry = cache_.peek(key);
208 const entry& e = *opt_entry;
221 bool erase(
const Key& key) {
return cache_.erase(key); }
248 cache_.remove_if([now](
const auto&
pair) {
return pair.
second.expiry < now; });
254NEFORCE_END_NAMESPACE__
NEFORCE_NODISCARD size_type size() const noexcept
获取当前缓存大小
NEFORCE_NODISCARD optional< Value > get(const Key &key)
获取缓存项
@ on_access
访问时刷新,每次访问都重置过期时间
@ sliding_window
滑动窗口,每次访问延长TTL
clock::time_point time_point
时间点类型
void enable_cleanup(duration interval=seconds(1))
启用后台清理线程
clock::duration duration
持续时间类型
NEFORCE_NODISCARD size_type capacity() const noexcept
获取缓存容量
void put(const Key &key, const Value &value)
插入缓存项(使用默认TTL)
void set_refresh_policy(refresh_policy policy)
设置刷新策略
void put(const Key &key, const Value &value, duration ttl)
插入缓存项(指定TTL)
void disable_cleanup()
禁用后台清理线程
bool erase(const Key &key)
删除缓存项
NEFORCE_NODISCARD bool contains(const Key &key)
检查缓存是否包含指定键
ttl_cache(size_type capacity, duration default_ttl=seconds(60))
构造函数
unsigned char uint8_t
8位无符号整数类型
duration< int64_t > seconds
秒持续时间
NEFORCE_INLINE17 constexpr none_t none
默认空表示
static time_point now() noexcept
获取当前时间点
nanoseconds duration
持续时间类型
_NEFORCE time_point< steady_clock > time_point
时间点类型