Enterprise Library Step By Step系列(十):缓冲应用程序块——进阶篇
作者:Terrylee
一.基于时间的过期策略
基于时间的过期策略,支持两种相对时间和绝对时间。
1.绝对时间(Absolute):
允许您定义一个缓冲项的生命周期,我们可以指定一个单一的时间作为过期,或者通过表达式来设置。
指定单一的时间作为过期:
1
/**/
///读取数据
2
Database db
=
DatabaseFactory.CreateDatabase(
"
Database Instance
"
);
3
DataSet ds
=
db.ExecuteDataSet(CommandType.Text,
"
Select * from Products
"
);
4
5

/**/
///创建CacheManager
6
IsolatedCacheManager
=
CacheFactory.GetCacheManager(
"
Isolated Cache Manager
"
);
7
8

/**/
///创建一个单一的时间
9
DateTime refreshTime
=
new
DateTime(
2005
,
11
,
12
,
12
,
51
,
30
);
10

11

/**/
///指定为绝对过期时间
12
AbsoluteTime expireTime
=
new
AbsoluteTime(refreshTime);
13
14

/**/
///添加缓冲项,优先级为Normal
15
IsolatedCacheManager.Add(
"
MyDataSet
"
,ds, CacheItemPriority.Normal,
null
,expireTime);
用表达式来设置:
表达式的格式:<Minute> <Hour> <Day of month> <Month> <Day of week>
例子:
“* * * * *” expires every minute
“5 * * * *” expire 5th minute of every hour
“* 21 * * *” expire every minute of the 21st hour of every day
“31 15 * * *” expire
3:31 PM
every day
“7 4 * * 6” expire Saturday
4:07 AM
“15 21 4 7 *” expire
9:15 PM
on 4 July
1
/**/
///读取数据
2
Database db
=
DatabaseFactory.CreateDatabase(
"
Database Instance
"
);
3
DataSet ds
=
db.ExecuteDataSet(CommandType.Text,
"
Select * from Products
"
);
4
5

/**/
///创建CacheManager
6
IsolatedCacheManager
=
CacheFactory.GetCacheManager(
"
Isolated Cache Manager
"
);
7
8

/**/
///创建基于表达式
9
ExtendedFormatTime expireTime
=
new
ExtendedFormatTime(
"
0 0 * * 6
"
);
10
11

/**/
///添加缓冲项,优先级为Normal,过期时间
12
IsolatedCacheManager.Add(
"
Key1
"
,
"
Cache Item1
"
, CacheItemPriority.Normal,
null
, expireTime);
2.变化的时间:
允许您定义针对条目的被调用的两次之间的间隔,定义条目的生命周期
1
/**/
///读取数据
2
Database db
=
DatabaseFactory.CreateDatabase(
"
Database Instance
"
);
3
DataSet ds
=
db.ExecuteDataSet(CommandType.Text,
"
Select * from Products
"
);
4
5

/**/
///创建CacheManager
6
IsolatedCacheManager
=
CacheFactory.GetCacheManager(
"
Isolated Cache Manager
"
);
7
8

/**/
///访问5分钟后过期,变化的时间
9
TimeSpan refreshTime
=
new
TimeSpan(
0
,
5
,
0
);
10
SlidingTime expireTime
=
new
SlidingTime(refreshTime);
11
12

/**/
///添加缓冲项
13
IsolatedCacheManager.Add(
"
Key1
"
,
"
Cache Item1
"
, CacheItemPriority.Normal,
null
, expireTime);
二.基于提醒机制的过期策略:
下面以文件依赖为例
1
/**/
///依赖于文件DependencyFile.txt
2
///当文件改变时过期
3
FileDependency expireNotice
=
new
FileDependency(
"
DependencyFile.txt
"
);
4
5

/**/
///添加缓冲项
6
myCacheManager.Add(
"
FileKey
"
,
"
String: Test Cache Item Dependency
"
, CacheItemPriority.Normal,
null
, expireNotice);
可以创建自己的过期类,需要实现 ICacheItemExpiration接口
三.条目移除的提示:
• Caching Application Block 提供了项目移除的提醒,并在一下情况下被激活
– 条目过期了
– 条目被显式的移除了
– 条目被策略的清楚了
• 需要实现 ICacheItemRefreshAction接口
• 一个类实现了 ICacheItemRefreshAction 接口,同时如果需要后端存储时,还必须被标识为 Serializable (Especially for persistent backing store)
1
[Serializable]
2
public
class
ProductCacheRefreshAction : ICacheItemRefreshAction
3

{
4
public void Refresh(string key, object expiredValue, CacheItemRemovedReason removalReason)
5
{
6
//……
7
}
8
}
四.装载缓冲:
1.缓冲的前期装载(Proactive loading):应用启动时装载
(1)优点
• 全部装载后,应用运行性能提升明显
(2)缺点
• 启动时间长
• 可能带来不必要的资源浪费
• 为了提升启动性能而进行的——基于不同线程的装载,有造成了应用结构的复杂性
(3)何时使用主动装载(Proactive caching)
在一些情况下中,他们自己有更新周期。当装载到缓冲将导致状态过期的出现
此时,您需要清楚的知道被缓冲的对象的生命周期
您还需要提前知道占用资源的程度
使用不稳定的资源时,尽量多使用主动装载缓冲
(4)主动装载实例:
1
CacheManager productsCache
=
CacheManager.GetCacheManager();
2

/**/
/// 获取数据
3
ArrayList list
=
dataProvider.GetProductList();
4

5

/**/
/// 添加缓冲项for (int i = 0; i < list.Count; i++)
6
{
7
Product product
=
(Product) list[i];
8
productsCache.Add( product.ProductID, product );
9
}
10
2.缓冲的被动装载(Reactive loading):按需装载
(1)优点
• 只有在需要的时候才装载,对资源的需求小
(2)缺点
• 但是在首次装载的时候,速度慢
(3)何时使用被动装载
需要缓冲的对象状态过多或系统资源不足的情况
资源的可靠性和性能良好,此时被动装载的又是更明显
希望利用缓冲机制,但是在应用程序的初始化时,希望不使用缓冲,而是根据用户输入等条件,进行缓冲
(4)被动装载实例:
1
CacheManager productsCache
=
CacheManager.GetCacheManager();
2
Product product
=
(Product) productsCache.GetData(productID);
3
if
(product
==
null
)
4

{
5
/**////
6
product = dataProvider.GetProductByID(productID);
7
if (product != null)
8
{
9
productsCache.Add(productID, product);
10
}
11
}
12
五.刷新缓冲(Explicit flushing):
1.精确刷新:
使用代码——Initiated by application code
全部移除——Removes all items from the cache
2.自我移除(Scavenging):
使用应用程序块的功能——Initiated by application block
基于优先级和最后访问的时间——Based upon priority and last access time
控制移除的精确度——Configuration settings control size of cache and number removed
自我清除的配置:
MaximumElementsLnCacheBeforeScavenging:缓冲中的最大元素数量。。
NumberToRemoveWhenScavenging:一次移除的数量。
为缓冲建立优先级
1
/**/
/// <summary>
2
/// 缓冲的优先级有以下几个值:
3
/// --Low
4
/// --Normal
5
/// --High
6
///--NotRemovable
7
/// </summary>
8
/// <param name="sender"></param>
9
/// <param name="e"></param>
10
private
void
button2_Click(
object
sender, System.EventArgs e)
11

{
12
for(int intCount=0; intCount<8; intCount++)
13
{
14
string strKeyName = "Key"+System.Convert.ToString(intCount);
15
16
if (intCount%2 == 0)
17
{
18
myCacheManager.Add(strKeyName, "High", CacheItemPriority.High, null, null);
19
}
20
else
21
{
22
myCacheManager.Add(strKeyName, "Low", CacheItemPriority.Low, null, null);
23
}
24
}
25
}