Today we're talking about using SqlCacheDependency in the cache. Its application scenario is IP address shielding, the database has a table ipblocked, recorded the blocked IP. The IP mask table does not change frequently, so you need to use caching because you want to check IP every time you register or try to log on. And the cache relies on the data table, that is, if the data in the table has changed, the cache should be invalidated.
It's so sleepy, it's not much, I'll give you the procedure here.
1. Modify web.config and enable SqlCacheDependency. Add the following code to the Web.config <system.web> section:
<caching>
<sqlCacheDependency enabled="true">
<databases>
<add connectionStringName="regex_libConnectionString" name="IPBlockedDependency"/>
</databases>
</sqlCacheDependency>
</caching>
The connectionstringname here specifies a connection string that is added to the <connectionStrings>. Name is the named SqlCacheDependency, which will be used in step 3rd.
2. Enable cache dependency for the database by executing the following command:
C:\Program Files\Microsoft Visual Studio 9.0\vc>aspnet_regsql-c "Data source=.;i Nitial catalog=regex-lib;integrated security=true "-ed-et-t" ipblocked "
The string following the-C is the connection string (please replace the value you want), and the string following the-t argument is the name of the datasheet. After the command is executed, a aspnet_sqlcachetablesforchangenotification table appears in the database.
3. Use caching in your code and set SqlCacheDependency dependencies for it:
private static string[] GetBlockedIPs()
{
// 1尝试从缓存中读取
string[] ips = (string[])HttpContext.Current.Cache[BlockedIPCacheKey];
if (ips != null)
return ips;
// 2从数据库中读取
using (RxDataContext db = new RxDataContext())
{
ips = db.IPBlockeds.Select(ipb => ipb.UserIP).ToArray();
}
// 3放入缓存
SqlCacheDependency depend = new SqlCacheDependency("IPBlockedDependency", "IPBlocked");
HttpContext.Current.Cache.Insert(BlockedIPCacheKey, ips, depend);
return ips;
}
When you create a sqlcachedependency, you specify the SqlCacheDependency name defined in Web.config and specify the name of the datasheet.
OK, this is just a list of steps, or it can be used as a checklist.