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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
|
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Runtime.Caching;
using
System.Text;
using
System.Threading.Tasks;
namespace
AutoLogisticsPH.Common.Utils
{
/// <summary>
/// 基于MemoryCache(内存缓存)的缓存工具类
/// Author:左文俊
/// Date:2017/12/11
/// </summary>
public
static
class
MemoryCacheUtil
{
private
static
readonly
Object _locker =
new
object
(), _locker2 =
new
object
();
/// <summary>
/// 取缓存项,如果不存在则返回空
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <returns></returns>
public
static
T GetCacheItem<T>(String key)
{
try
{
return
(T)MemoryCache.Default[key];
}
catch
{
return
default
(T);
}
}
/// <summary>
/// 是否包含指定键的缓存项
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public
static
bool
Contains(
string
key)
{
return
MemoryCache.Default.Contains(key);
}
/// <summary>
/// 取缓存项,如果不存在则新增缓存项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="cachePopulate"></param>
/// <param name="slidingExpiration"></param>
/// <param name="absoluteExpiration"></param>
/// <returns></returns>
public
static
T GetOrAddCacheItem<T>(String key, Func<T> cachePopulate, TimeSpan? slidingExpiration =
null
, DateTime? absoluteExpiration =
null
)
{
if
(String.IsNullOrWhiteSpace(key))
throw
new
ArgumentException(
"Invalid cache key"
);
if
(cachePopulate ==
null
)
throw
new
ArgumentNullException(
"cachePopulate"
);
if
(slidingExpiration ==
null
&& absoluteExpiration ==
null
)
throw
new
ArgumentException(
"Either a sliding expiration or absolute must be provided"
);
if
(MemoryCache.Default[key] ==
null
)
{
lock
(_locker)
{
if
(MemoryCache.Default[key] ==
null
)
{
T cacheValue = cachePopulate();
if
(!
typeof
(T).IsValueType && ((
object
)cacheValue) ==
null
)
//如果是引用类型且为NULL则不存缓存
{
return
cacheValue;
}
var
item =
new
CacheItem(key, cacheValue);
var
policy = CreatePolicy(slidingExpiration, absoluteExpiration);
MemoryCache.Default.Add(item, policy);
}
}
}
return
(T)MemoryCache.Default[key];
}
/// <summary>
/// 取缓存项,如果不存在则新增缓存项
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="cachePopulate"></param>
/// <param name="dependencyFilePath"></param>
/// <returns></returns>
public
static
T GetOrAddCacheItem<T>(String key, Func<T> cachePopulate,
string
dependencyFilePath)
{
if
(String.IsNullOrWhiteSpace(key))
throw
new
ArgumentException(
"Invalid cache key"
);
if
(cachePopulate ==
null
)
throw
new
ArgumentNullException(
"cachePopulate"
);
if
(MemoryCache.Default[key] ==
null
)
{
lock
(_locker2)
{
if
(MemoryCache.Default[key] ==
null
)
{
T cacheValue = cachePopulate();
if
(!
typeof
(T).IsValueType && ((
object
)cacheValue) ==
null
)
//如果是引用类型且为NULL则不存缓存
{
return
cacheValue;
}
var
item =
new
CacheItem(key, cacheValue);
var
policy = CreatePolicy(dependencyFilePath);
MemoryCache.Default.Add(item, policy);
}
}
}
return
(T)MemoryCache.Default[key];
}
/// <summary>
/// 移除指定键的缓存项
/// </summary>
/// <param name="key"></param>
public
static
void
RemoveCacheItem(
string
key)
{
try
{
MemoryCache.Default.Remove(key);
}
catch
{ }
}
private
static
CacheItemPolicy CreatePolicy(TimeSpan? slidingExpiration, DateTime? absoluteExpiration)
{
var
policy =
new
CacheItemPolicy();
if
(absoluteExpiration.HasValue)
{
policy.AbsoluteExpiration = absoluteExpiration.Value;
}
else
if
(slidingExpiration.HasValue)
{
policy.SlidingExpiration = slidingExpiration.Value;
}
policy.Priority = CacheItemPriority.Default;
return
policy;
}
private
static
CacheItemPolicy CreatePolicy(
string
filePath)
{
CacheItemPolicy policy =
new
CacheItemPolicy();
policy.ChangeMonitors.Add(
new
HostFileChangeMonitor(
new
List<
string
>() { filePath }));
policy.Priority = CacheItemPriority.Default;
return
policy;
}
}
}
|
支持:可指定绝对过期时间、滑动过期明间、文件依赖 三种缓存方式,目前已在公司各种生产业务项目中有使用。优点是可以根据数据的使用频率设置缓存有效期,特别是文件依赖缓存,比如:连接字符串读取一次后,若CONFIG文件没有改变,则缓存永久有效,一旦CONFIG更改,则缓存失效需重新读取,保证数据缓存的最大可用性,减少不必要的多次重复读取CONFIG。
使用示例很简单:(如下:会在第一次读取连接字符串并解密后返回给connstr变量,后续直接通过缓存KEY dbConnName直接返回连接字符串的结果,若修改了连接字符串的CONFIG文件,则缓存的项会失效,会重新读取连接字符串并重新加入到缓存中)
string connstr= MemoryCacheUtil.GetOrAddCacheItem(dbConnName, () =>
{
var connStrSettings = ConfigUtil.GetConnectionString(dbConnName,dbConnectionStringConfigPath);
string dbProdName = connStrSettings.ProviderName;
string dbConnStr = connStrSettings.ConnectionString;
return EncryptUtil.Decrypt(dbConnStr);
}, "缓存依赖文件路路,如:c:\app\app.config");
本文转自 梦在旅途 博客园博客,原文链接:http://www.cnblogs.com/zuowj/p/8440902.html ,如需转载请自行联系原作者