NBearV3教程——Cache篇

版本

1.0 [2006-11-18]

简介

本教程介绍NBearV3中的查询缓存支持。

目标

通过本教程,读者应能够全面掌握内置于NBearV3的查询缓存的使用。

代码

本教程不包含任何演示代码。

时间

<10分钟。

正文

1 配置及启用NBearV3中的缓存功能

要启用缓存支持,需要在Web.configApp.config中添加cacheConfig配置节:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
 
<configSections>
    
<section name="entityConfig" type="NBear.Common.EntityConfigurationSection, NBear.Common" />
    
<section name="cacheConfig" type="NBear.Data.CacheConfigurationSection, NBear.Data" />
 
</configSections>
 
<entityConfig>
    
<includes>
      
<add key="Sample" value="C:\Teddy\NBearV3\src\NBear.Test.UnitTests\EntityConfig.xml" />
    
</includes>
 
</entityConfig>
 
<cacheConfig enable="true">
    
<cachingTables>
      
<add key="Northwind.Orders" value="5" />
    
</cachingTables>
 
</cacheConfig>
 
<connectionStrings>
    
<add name="Northwind" connectionString="Server=(local);Database=Northwind;Uid=sa;Pwd=sa" providerName="NBear.Data.SqlServer.SqlDbProvider"/>
 
</connectionStrings>
</configuration>

注意代码中粗体的部分,首先在configSections中添加cacheConfig这个section。接着,添加一个cacheConfig配置节,其中的cachingTables中可以有多个add,每一个add中,key的值格式为AAA.BBBvalue代表缓存有效的时间长度,单位为秒。

AAA代表对应的ConnectionString中的name。比如这里的Northwind代表了名为NorthwindConnectionString

BBB代表数据库中实际的表名、视图名或存储过程名。

2 在代码中启用、禁用和使用自动缓存

一旦如上配置了启用缓存,则默认情况下,所有的NBear.Data.Gateway实例,默认将是开启了自动缓存功能的。相应的表、视图或存储过程被查询时,如果在config中设置为需要缓存的,则会被缓存。可以调用Gateway.TurnOnCache()TurnOffCache()方法开启和关闭一个Gateway的缓存支持。

在两种情况下,自动缓存会自动过期失效。一是被缓存的数据超过config中设置的缓存过期时间;二是,指定的过期时间还没到,但是,此时执行了对该实体的强类型写操作。所谓强类型写操作,指Gateway.Delete/Save/BatchDelete/BatchUpdate等这些带范型参数列表EntityType的范型方法。

注:所有缓存数据是作为一个Gateway的静态变量,对所有的Gateway可见并共享的。也就是说,即使有多个Gateway实例,他们共享所有的缓存数据。并且,即使一个禁用了缓存的Gateway实例,对他执行的强类型写数据库操作,也会导致全局的Gateway缓存中的对应实体的缓存数据过期。

3 在代码中使用自定义缓存

除了默认的自动缓存之外,也可以手动的使用自定义缓存。任何时候,我们都可以使用任何Gateway实例的AddCache()/GetCache()/RemoveCache()RemoveCaches()方法手动读写和删除缓存对象。

//正文结束

//本文结束

posted @ 2006-11-21 10:17  Teddy's Knowledge Base  Views(10548)  Comments(6Edit  收藏  举报