首先我是做web开发的,所以很多会偏向web的,组件使用的缓存是System.Web.HttpRuntime.Cache。
组件在默认情况下是关闭缓存的。
所以要开启缓存查询要做一下配置。
先看一下例子配置:
<configSections> <section name="HxjCacheConfig" type="Hxj.Data.CacheConfiguration,Hxj.Data"/> </configSections> <HxjCacheConfig enable="true"> <entities> <add key="NorthwindConnectionString.Products" value="60"></add> </entities> </HxjCacheConfig> <connectionStrings> <add name="NorthwindConnectionString" connectionString="Data Source=ricci\hu;Initial Catalog=Northwind;Integrated Security=True" providerName="System.Data.SqlClient"/> </connectionStrings>
HxjCacheConfig 节点的 enable 表示是否开启缓存,默认是关闭状态,除非显式开启 enable="true"。
entities 节点下的配置就是对实体查询的缓存配置。
<add key="NorthwindConnectionString.Products" value="60"></add>
表示connectionStrings中的节点name="NorthwindConnectionString"的连接下的Products表配置.
value="60" 表示缓存60秒。
所以一定要connectionStrings的name加上实体名,不然配置无效。
当然value也可以是缓存依赖的文件。
<add key="NorthwindConnectionString.Products" value="1.txt"></add>
表示Products表的查询缓存依赖程序根目录下的1.txt文件。组件会判断该文件是否存在,不存在则该配置无效。
那测试一下缓存配置。
List<Products> list = new List<Products>(); for (int i = 0; i < 2; i++) { list.Add(DbSession.Default.From<Products>().ToFirst()); } for (int i = 0; i < 3; i++) { list.Add(DbSession.Default.From<Products>().ToFirst()); }
看一下组件执行的sql:
Parameters: @d786265aa9bd40bfbc253814d6c16b13[Int32] = 1
执行了5次查询。
再设置 enable="true",开启缓存。
再查看一下执行的sql:
Parameters: @075ce07012884a21878604c197ddb7cc[Int32] = 1
只执行了一次sql连接。
后面的四次都是直接从缓存中读取的。
再次执行,所有的查询都是直接从缓存中返回回来,没有连接数据库。
测试缓存文件依赖:
List<Products> list = new List<Products>(); for (int i = 0; i < 2; i++) { list.Add(DbSession.Default.From<Products>().Where(Products._.ProductID == 3).ToFirst()); } FileHelper.AppendText(Server.MapPath("~/1.txt"), "abc");
System.Threading.Thread.Sleep(2000);
for (int i = 0; i < 3; i++) { list.Add(DbSession.Default.From<Products>().Where(Products._.ProductID == 3).ToFirst()); }
查看sql:
Parameters: @e614d6bbc84c4603b159e30644665e07[Int32] = 3
执行了两次,当修改文件后,缓存失效重新从数据库查询数据。
其实测试的有时候输出一条sql,可能是执行的太快,缓存失效来不及。
所以后来才加了System.Threading.Thread.Sleep(2000);
再次刷新,就只输出一条sql,只执行一次,也就是修改1.txt文件后才重新查询数据库。
查询判断是否有缓存配置是根据 From<Products>()这里的Products来判断是否存在缓存配置的。
对于ToDataReader()查询,是不会缓存的。
当然用到ToDataReader的查询的其他方法也不会缓存,例如上一节中的Exists<TEntity>(WhereClip where)方法。
下一节将讲述自定义缓存。