您的位置:首页 > 其它

基于Boost.MultiIndex实现的Session管理器

2014-08-03 17:53 405 查看
#ifndef SESSION_MANAGER_
#define SESSION_MANAGER_

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <stdint.h>

template <typename T>
class SessionManager
{
public:
SessionManager(size_t max_size = 10000, uint64_t timeout = 3) : max_size_(max_size), timeout_(timeout) {}
private:
SessionManager(const SessionManager &);
SessionManager & operator = (const SessionManager &);

public:
int Init(size_t max_size, uint64_t timeout)
{
storage_.clear();
max_size_ = max_size;
timeout_ = timeout;
return 0;
}

int Insert(uint64_t id, uint64_t time, const T &entry, bool force = false)
{
IdIndex &index = storage_.template get<IdTag>();
typename IdIndex::iterator iter = index.find(id);
if (iter != index.end()) return -1;
if (index.size() >= max_size_) {
if (!force) return -2;
TimeIndex &time_index = storage_.template get<TimeTag>();
time_index.erase(time_index.begin());
}
index.insert(Entry(id, time, entry));
return 0;
}

int Fetch(uint64_t id, uint64_t time, T &entry)
{
IdIndex &index = storage_.template get<IdTag>();
typename IdIndex::iterator iter = index.find(id);
if (iter == index.end()) return -1;
if (time != 0) index.modify(iter, TimeModifier(time));
entry = iter->entry;
return 0;
}

void Delete(uint64_t id)
{
IdIndex &index = storage_.template get<IdTag>();
index.erase(id);
}

void Scan(uint64_t time)
{
TimeIndex &index = storage_.template get<TimeTag>();
for (typename TimeIndex::iterator iter = index.begin(); iter != index.end(); ) {
if (iter->time + timeout_ > time) return;
iter = index.erase(iter);
}
}

size_t Size() const { return storage_.size(); }

private:
struct Entry
{
uint64_t id;
uint64_t time;
T entry;
Entry(uint64_t id, uint64_t time, const T &entry) : id(id), time(time), entry(entry) {}
};

struct TimeModifier
{
int new_time;
TimeModifier(int new_time) : new_time(new_time) {}
void operator () (Entry &entry)
{
entry.time = new_time;
}
};

struct IdTag {};
struct TimeTag {};

typedef boost::multi_index_container<
Entry,
boost::multi_index::indexed_by<
boost::multi_index::hashed_unique<boost::multi_index::tag<IdTag>, boost::multi_index::member<Entry, uint64_t, &Entry::id> >,
boost::multi_index::ordered_non_unique<boost::multi_index::tag<TimeTag>, boost::multi_index::member<Entry, uint64_t, &Entry::time> >
>
> Storage;

typedef typename Storage::template index<IdTag>::type IdIndex;
typedef typename Storage::template index<TimeTag>::type TimeIndex;

private:
Storage storage_;
size_t max_size_;
uint64_t timeout_;
};

#endif
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: