Enterprise Library——企业库缓存应用程序块

简介:

提供了一些方便易用的、可扩展的缓冲机制。
这些缓冲机制可以使用在整体应用中的各个层面。
支持后期存储,支持的存储方式包括数据库方式和独立存储方式(Isolated storage), 便于应用方便的重新启动
便于使用
便于配置
支持使用配置工具
线程安全
可以确保在内存中的缓冲和后端存储保持同步
1.创建配置文件
在您的应用配置文件中增加一个缓冲应用
为要创建的数据项创建 Cache manager
每一个子项需要有独立的名字
确定哪一个是默认的Cache manager
%E5%9B%BE%E7%89%871.png
内存驻留型缓冲的典型应用: 
应用程序经常使用同样的数据
一个应用程序经常需要重新获得数据
磁盘驻留型缓冲的典型应用: 
数据量比较大
同时,从应用服务提供商(例如数据库)重新获取数据,开销比较大
在缓冲的生命周期中,必须经历系统的重新启动
创建默认 cache manager
CacheManager myCache = CacheManager.GetCacheManager(); 
创建命名的cache manager
CacheManager productsCache = 
       CacheManager.GetCacheManager(“Products”); 
默认的增加一个条目
productsCache.Add(“ProductID123”, productObject); 
基于时间的过期实例
DateTime refreshTime = new DateTime(2005, 3, 21, 2, 0, 0);
AbsoluteTime expireTime = new AbsoluteTime(refreshTime);
     
primitivesCache.Add("Key1", "Cache Item1", CacheItemPriority.Normal,
                                      null, expireTime);
变化时间的过期
被访问5分钟后
TimeSpan refreshTime = new TimeSpan(0, 5, 0);
SlidingTime expireTime = new SlidingTime(refreshTime);
     
primitivesCache.Add("Key1", "Cache Item1", CacheItemPriority.Normal,
                                      null, expireTime);
扩展时间应用范例
ExtendedFormatTime expireTime = 
  new ExtendedFormatTime("0 0 * * 6");
     
primitivesCache.Add("Key1", "Cache Item1", CacheItemPriority.Normal,
                                      null, expireTime);
基于提醒机制的过期  文件依赖的例子
FileDependency expireNotice = new FileDependency(“Trigger.txt”);
    
productsCache.Add("Key1", "Cache Item1", CacheItemPriority.Normal,
                                      null, expireNotice);
配置过期表决的频率
通过后台线程(BackgroundScheduler),移除过期事项
您可以对次线程进行配置
过高:CPU浪费,且CACHE没有起到作用
过低:内存消耗太大
建议使用性能计数器监视一下
%E5%9B%BE%E7%89%872.png
条目移除提示
Caching Application Block 提供了项目移除的提醒,并在一下情况下被激活
条目过期了
条目被显式的移除了
条目被策略的清楚了
需要实现 ICacheItemRefreshAction接口
一个类实现了 ICacheItemRefreshAction 接口,同时如果需要后端存储时,还必须被标识为 Serializable (Especially for persistent backing store)
[Serializable]
public class ProductCacheRefreshAction : ICacheItemRefreshAction
{
    public void Refresh(string key, object expiredValue, 
                        CacheItemRemovedReason removalReason)
    {
      // Item has been removed from cache. 
      // Perform desired actions here,
      // based upon the removal reason (e.g. refresh the cache with the     
      // item).
    }
}
从Cache manager中获取
类型要正确
一定要检查空值 (item not found in cache)
public Product ReadProductByID(string productID)
{
     Product product = (Product)cache.GetData(productID);

    if (product == null)
    {
        // Item not in cache
    }
}
装载缓冲
缓冲的前期装载(Proactive loading)
应用启动时装载
优点
全部装载后,应用运行性能提升明显
缺点
启动时间长
可能带来不必要的资源浪费  
为了提升启动性能而进行的——基于不同线程的装载,有造成了应用结构的复杂性
缓冲的被动装载(Reactive loading)
按需装载
优点
只有在需要的时候才装载,对资源的需求小
缺点
但是在首次装载的时候,速度慢
主动装载的实例
1:Create cache manager
CacheManager productsCache = CacheManager.GetCacheManager(); 
2:Add items during component initialization
// Retrieve the data from the source
ArrayList list = dataProvider.GetProductList();

// Add all the items to the cache
for (int i = 0; i < list.Count; i++) 

    Product product = (Product) list[i]; 
    productsCache.Add( product.ProductID, product ); 

后期装载的实例
1:Create cache manager
CacheManager productsCache = CacheManager.GetCacheManager(); 
2:Add items when retrieved from data source
Product product = (Product) productsCache.GetData(productID); 
if (product == null) 

    // Retrieve it from the data provider 
    // and cache it for more requests. 
    product = dataProvider.GetProductByID(productID);
    if (product != null) 
    { 
       productsCache.Add(productID, product); 
    } 

从缓冲中移除
1:Remove item with specified key
productsCache.Remove(“Product101Key”)
2:No error occurs if key is not found
因此通过这种方法,不能知道ITEM是否移除了
如果对象实现了ICacheRefreshItemAction,可以有信息
刷新缓冲
productsCache.Flush()
为缓冲建立优先级
productsCache.Add("Key1", "Cache Item1", CacheItemPriority.High,
                   new ProductCacheRefreshAction(), expireNotice)

 实例

None.gif using  System;
None.gif
using  System.Drawing;
None.gif
using  System.Collections;
None.gif
using  System.ComponentModel;
None.gif
using  System.Windows.Forms;
None.gif
using  System.Data;
None.gif
None.gif
using  Microsoft.Practices.EnterpriseLibrary.Caching;
None.gif
using  Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
None.gif
using  Microsoft.Practices.EnterpriseLibrary.Data;
None.gif
None.gif
None.gif
namespace  CacheWindowsApplication
ExpandedBlockStart.gif
{
ExpandedSubBlockStart.gif    
/// <summary>
InBlock.gif    
/// Form1 的摘要说明。
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public class Form1 : System.Windows.Forms.Form
ExpandedSubBlockStart.gif    
{
InBlock.gif        
private System.Windows.Forms.Button btnQuery;
ExpandedSubBlockStart.gif        
/// <summary>
InBlock.gif        
/// 必需的设计器变量。
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private System.ComponentModel.Container components = null;
InBlock.gif        
private System.Windows.Forms.Label label;
InBlock.gif        
private System.Windows.Forms.ListBox listBox;
InBlock.gif        
private System.Windows.Forms.Button btnGetFromCache;
InBlock.gif
InBlock.gif        
// **********************************************
InBlock.gif        
// Define parameters for demonstration
InBlock.gif        
//***********************************************
InBlock.gif
        private IDataReader myDr = null;
InBlock.gif        
private System.Windows.Forms.Button btnTestExpire;
InBlock.gif        
private CacheManager myCacheManager = null;
InBlock.gif        
private System.Windows.Forms.Button btnReview;
InBlock.gif        
private System.Windows.Forms.Button btnFileDependency;
InBlock.gif        
private System.Windows.Forms.Button btnQueryByFile;
InBlock.gif        
private System.Windows.Forms.Button button1;
InBlock.gif        
private System.Windows.Forms.Button button2;
InBlock.gif        
private System.Windows.Forms.Button button3;
InBlock.gif        
private CacheManager IsolatedCacheManager =null;
InBlock.gif
InBlock.gif        
public Form1()
ExpandedSubBlockStart.gif        
{
InBlock.gif            
//
InBlock.gif            
// Windows 窗体设计器支持所必需的
InBlock.gif            
//
InBlock.gif
            InitializeComponent();
InBlock.gif
InBlock.gif            
//
InBlock.gif            
// TODO: 在 InitializeComponent 调用后添加任何构造函数代码
InBlock.gif            
//
ExpandedSubBlockEnd.gif
        }

InBlock.gif
ExpandedSubBlockStart.gif        
/// <summary>
InBlock.gif        
/// 清理所有正在使用的资源。
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        protected override void Dispose( bool disposing )
ExpandedSubBlockStart.gif        
{
InBlock.gif            
if( disposing )
ExpandedSubBlockStart.gif            
{
InBlock.gif                
if (components != null
ExpandedSubBlockStart.gif                
{
InBlock.gif                    components.Dispose();
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
base.Dispose( disposing );
ExpandedSubBlockEnd.gif        }

InBlock.gif
ContractedSubBlock.gif        
Windows 窗体设计器生成的代码
InBlock.gif
ExpandedSubBlockStart.gif        
/// <summary>
InBlock.gif        
/// 应用程序的主入口点。
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        [STAThread]
InBlock.gif        
static void Main() 
ExpandedSubBlockStart.gif        
{
InBlock.gif            Application.Run(
new Form1());
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnQuery_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{        
InBlock.gif            
this.label.Text = System.Convert.ToString(myCacheManager.Count);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void Form1_Load(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            Database db 
= DatabaseFactory.CreateDatabase("Database Instance");
InBlock.gif            IDataReader dr 
= db.ExecuteReader(CommandType.Text,"Select * from Products");
InBlock.gif
InBlock.gif            
this.myDr=dr;
InBlock.gif            
InBlock.gif            myCacheManager 
= CacheFactory.GetCacheManager();
InBlock.gif            myCacheManager.Add(
"MyDataReader",this.myDr);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnGetFromCache_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            IDataReader toBeDisplay 
= (IDataReader)myCacheManager.GetData("MyDataReader");
InBlock.gif            
InBlock.gif            
if(toBeDisplay != null)
ExpandedSubBlockStart.gif            
{
InBlock.gif                
while(toBeDisplay.Read())
ExpandedSubBlockStart.gif                
{
InBlock.gif                    
this.listBox.Items.Add(toBeDisplay.GetValue(2));
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnTestExpire_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            Database db 
= DatabaseFactory.CreateDatabase("Database Instance");
InBlock.gif            DataSet ds 
= db.ExecuteDataSet(CommandType.Text,"Select * from Products");
InBlock.gif        
InBlock.gif            IsolatedCacheManager 
= CacheFactory.GetCacheManager("Isolated Cache Manager");
InBlock.gif            
InBlock.gif            DateTime refreshTime 
= new DateTime(2005624125130);
InBlock.gif            AbsoluteTime expireTime 
= new AbsoluteTime(refreshTime);
InBlock.gif                    
InBlock.gif            IsolatedCacheManager.Add(
"MyDataSet",ds, CacheItemPriority.Normal, null,expireTime);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnReview_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            
this.label.Text = System.Convert.ToString(IsolatedCacheManager.Count);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button1_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif        
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnFileDependency_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            FileDependency expireNotice 
= new FileDependency("DependencyFile.txt");
InBlock.gif                
InBlock.gif            myCacheManager.Add(
"FileKey""String: Test Cache Item Dependency", CacheItemPriority.Normal, null, expireNotice);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void btnQueryByFile_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            
this.label.Text = System.Convert.ToString(myCacheManager.Count);
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button1_Click_1(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            myCacheManager.Remove(
"FileKey");
ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button2_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            
for(int intCount=0; intCount<8; intCount++)
ExpandedSubBlockStart.gif            
{
InBlock.gif                
string strKeyName = "Key"+System.Convert.ToString(intCount);
InBlock.gif                
InBlock.gif                
if (intCount%2 == 0)
ExpandedSubBlockStart.gif                
{
InBlock.gif                    myCacheManager.Add(strKeyName, 
"High", CacheItemPriority.High, nullnull);
ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gif                
{
InBlock.gif                    myCacheManager.Add(strKeyName, 
"Low", CacheItemPriority.Low, nullnull);
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void button3_Click(object sender, System.EventArgs e)
ExpandedSubBlockStart.gif        
{
InBlock.gif            
for(int intCount=0; intCount<5; intCount++)
ExpandedSubBlockStart.gif            
{
InBlock.gif                
string strKeyName = "HighKey"+System.Convert.ToString(intCount);
InBlock.gif                myCacheManager.Add(strKeyName, 
"High", CacheItemPriority.High, nullnull);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif



本文转自高海东博客园博客,原文链接:http://www.cnblogs.com/ghd258/archive/2005/10/28/263760.html,如需转载请自行联系原作者
相关文章
|
2月前
|
缓存 Java 数据库
优化您的Spring应用程序:缓存注解的精要指南
优化您的Spring应用程序:缓存注解的精要指南
45 0
|
29天前
|
存储 缓存 移动开发
HTML5 应用程序缓存
HTML5的离线缓存(Application Cache)允许网页存储资源以实现离线访问。通过manifest文件指定缓存内容和更新规则,比如列出要缓存的HTML、CSS、JS和图片。在HTML中引用manifest文件后,浏览器会根据文件变化更新缓存。但要注意,应用缓存不自动更新,需手动修改manifest触发,并且现代Web开发更多使用服务工作者(Service Workers)替代,以获得更优的离线体验和更新策略。
|
9月前
|
存储 缓存 数据库
极速Python编程:利用缓存加速你的应用程序
在软件开发中,缓存是一种常用的技术,用于提高系统性能和响应速度。Python提供了多种缓存技术和库,使我们能够轻松地实现缓存功能。本文将带您从入门到精通,逐步介绍Python中的缓存使用方法,并提供实例演示。
223 0
|
存储 缓存 移动开发
前端开发面试题—HTML5应用程序缓存 (离线存储)
今天分享一下我遇到的前端面试题,什么是HTML5应用程序缓存 (离线存储) ?
202 0
前端开发面试题—HTML5应用程序缓存 (离线存储)
|
缓存 Java
面经 - 【多线程】在Java中Lock接口比synchronized块的优势是什么?你需要实现一个高效的缓存,它允许多个用户读,但只允许一个用户写,以此来保持它的完整性,你会怎样去实现它?
面经 - 【多线程】在Java中Lock接口比synchronized块的优势是什么?你需要实现一个高效的缓存,它允许多个用户读,但只允许一个用户写,以此来保持它的完整性,你会怎样去实现它?
357 0
|
缓存 前端开发 JavaScript
前端培训-中级阶段(23)- Manifest ApplicationCache应用程序缓存(2019-10-31期)
前端最基础的就是 HTML+CSS+Javascript。掌握了这三门技术就算入门,但也仅仅是入门,现在前端开发的定义已经远远不止这些。前端小课堂(HTML/CSS/JS),本着提升技术水平,打牢基础知识的中心思想,我们开课啦(每周四)。
152 0
前端培训-中级阶段(23)- Manifest  ApplicationCache应用程序缓存(2019-10-31期)
|
缓存 区块链 Windows
应用程序图标设置 系统图标缓存问题
应用程序图标设置 系统图标缓存问题
161 0
|
缓存 数据库 Windows
IIS应用程序池_缓存回收
原文:IIS应用程序池_缓存回收 本人最近由于公司业务,需要把问卷的问题和答案存入缓存中已提高问卷加载速度,减少数据库压力。 缓存关键代码(公司代码已做封装,这里只贴出关键代码): HttpRuntime.
1656 0
|
移动开发 缓存 JavaScript
html5应用程序缓存
缓存概念: ------页面缓存: html、JS、CSS等,这些缓存资源是由于浏览器的行为而产生;  ------数据缓存 ----------AppCache:  Cache Manifest 操作;  需要服务器  与 客户端  相互配合; 所有的缓存数据都由开发者直接完全地掌控。
1202 0

热门文章

最新文章