-
Notifications
You must be signed in to change notification settings - Fork 1
/
local_cache_cfg.h
95 lines (79 loc) · 2.27 KB
/
local_cache_cfg.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright [year] <Copyright Owner>
#ifndef LOCAL_CACHE_CFG_H_
#define LOCAL_CACHE_CFG_H_
#include <time.h>
#include <map>
template <class Tkey, class Tvalue>
class CacheCfg {
public:
CacheCfg();
CacheCfg(time_t timeout);
public:
void SetTimeOut(time_t t);
int get(const Tkey& key, Tvalue& value) const;
int get(const Tkey& key, time_t end_time, Tvalue& value) const;
void set(const Tkey& key, const Tvalue& value);
void set(const Tkey& key, const Tvalue& value, time_t end_time);
private:
typedef struct _Tcontent {
Tvalue value;
time_t expire;
} Tcontent;
std::map<Tkey, Tcontent> content;
time_t timeout;
};
template <class Tkey, class Tvalue>
CacheCfg<Tkey, Tvalue>::CacheCfg(time_t iTimeout) : timeout(iTimeout){};
template <class Tkey, class Tvalue>
CacheCfg<Tkey, Tvalue>::CacheCfg() : timeout(3600){};
template <class Tkey, class Tvalue>
void CacheCfg<Tkey, Tvalue>::SetTimeOut(time_t t) {
timeout = t;
};
template <class Tkey, class Tvalue>
void CacheCfg<Tkey, Tvalue>::set(const Tkey& key, const Tvalue& value) {
Tcontent con;
con.value = value;
con.expire = (time(NULL) + timeout);
content[key] = con;
return;
};
template <class Tkey, class Tvalue>
void CacheCfg<Tkey, Tvalue>::set(const Tkey& key, const Tvalue& value, time_t end_time) {
Tcontent con;
con.value = value;
con.expire = end_time;
content[key] = con;
return;
};
template <class Tkey, class Tvalue>
int CacheCfg<Tkey, Tvalue>::get(const Tkey& key, Tvalue& value) const {
typename map<Tkey, Tcontent>::const_iterator cit = content.find(key);
if (cit != content.end()) {
const Tcontent& con = cit->second;
value = con.value;
if (con.expire > time(NULL)) {
return 0;
} else {
return 2;
}
} else {
return 1;
}
};
template <class Tkey, class Tvalue>
int CacheCfg<Tkey, Tvalue>::get(const Tkey& key, time_t end_time, Tvalue& value) const {
typename map<Tkey, Tcontent>::const_iterator cit = content.find(key);
if (cit != content.end()) {
const Tcontent& con = cit->second;
value = con.value;
if (con.expire > end_time) {
return 0;
} else {
return 2;
}
} else {
return 1;
}
}
#endif // LOCAL_CACHE_CFG_H_