在VS中安装Memcached,直接在NuGet下搜索Memcached,选择第一个进行安装:
服务端资源下载地址:https://pan.baidu.com/s/1gf3tupl
接下来开始写程序,老规矩,直接上代码:
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
|
public
class
Memcached : ICache
{
private
static
readonly
MemcachedClient CacheClient =
new
MemcachedClient();
///
/// 获取缓存
///
///
///
///
public
T GetCache
string
cacheKey)
where
T :
class
{
try
{
return
(T)CacheClient.Get(cacheKey);
}
catch
{
return
default
(T);
}
}
///
/// 写入缓存,过期时间默认10分钟
///
///
///
///
public
void
WriteCache
string
cacheKey)
where
T :
class
{
//CacheClient.Store(StoreMode.Set, cacheKey, value);
CacheClient.Store(Exists(cacheKey) ? StoreMode.Set : StoreMode.Replace, cacheKey, value, DateTimeHelper.Now.AddMinutes(10));
}
///
/// 写入缓存
///
///
///
///
///
public
void
WriteCache
string
cacheKey, DateTime expireTime)
where
T :
class
{
//CacheClient.Store(StoreMode.Set, cacheKey, value, expireTime);
CacheClient.Store(Exists(cacheKey) ? StoreMode.Set : StoreMode.Replace, cacheKey, value, expireTime);
}
///
/// 移除缓存
///
///
public
void
RemoveCache(
string
cacheKey)
{
CacheClient.Remove(cacheKey);
}
///
/// 移除所有缓存
///
public
void
RemoveCache()
{
CacheClient.FlushAll();
}
///
/// 是否存在
///
///
///
private
static
bool
Exists(
string
key)
{
return
CacheClient.Get(key) !=
null
;
}
}
|
接口类:
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
|
public
interface
ICache
{
///
/// 读取缓存
///
/// 键
///
T GetCache
string
cacheKey)
where
T :
class
;
///
/// 写入缓存
///
/// 对象数据
/// 键
void
WriteCache
string
cacheKey)
where
T :
class
;
///
/// 写入缓存
///
/// 对象数据
/// 键
/// 到期时间
void
WriteCache
string
cacheKey, DateTime expireTime)
where
T :
class
;
///
/// 移除指定数据缓存
///
/// 键
void
RemoveCache(
string
cacheKey);
///
/// 移除全部缓存
///
void
RemoveCache();
}
|
配置文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
|
---------------------
作者:大师兄丶
来源:CNBLOGS
原文:https://www.cnblogs.com/zhao-yi/p/7826672.html
版权声明:本文为作者原创文章,转载请附上博文链接!