在ASP.NET MVC中应用分布式缓存它是最简单的方式,那么要使用Memcached ,我们就进行配置一番:
打开Web.config 文件,添加如下配置节点
view plaincopy to clipboardprint?
<section name="cacheProvider"
type="MemcachedProviders.Cache.CacheProviderSection, MemcachedProviders"
allowDefinition="MachineToApplication" restartOnExternalChanges="true"/>
<sectiongroup name="enyim.com">
<section name="memcached"
type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" />
</sectiongroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
添加如下节点指向Memcached服务器
view plaincopy to clipboardprint?
<enyim .com>
<memcached>
<servers>
<!-- 你的服务器-->
<add address="127.0.0.1" port="11211" />
</servers>
<socketpool minPoolSize="10" maxPoolSize="100"
connectionTimeout="00:00:10" deadTimeout="00:02:00" />
</memcached>
</enyim>
接着配置缓存驱动器
view plaincopy to clipboardprint?
<cacheprovider
defaultProvider="MemcachedCacheProvider">
<providers>
<add name="MemcachedCacheProvider"type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders"keySuffix="_MySuffix_" defaultExpireTime="2000"/>
</providers>
</cacheprovider>
继续配置log4j
view plaincopy to clipboardprint?
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout"><conversionpattern value="%date [%thread] %-5level %logger [%property{NDC}]- %message%newline" />
</layout></appender><root><priority value="WARN"/><appender -ref ref="ConsoleAppender">
<filter type="log4net.Filter.LevelRangeFilter">
<levelmin value="WARN"/><levelmax value="FATAL"/>
</filter>
</appender>
</root>
</log4net>
假如你引用了所有相关的类库,下面是我的category 控制器,如果Memcached内存中不包含returnObj对象,那么我们将缓存它
view plaincopy to clipboardprint?
public ActionResult Category()
{
var returnObj = DistCache.Get<list <CategoryObject>>("fullCatListObject");
if (returnObj == null)
{
P015.Modules.Categories.Categories _cat = new P015.Modules.Categories.Categories();
returnObj = _cat.getCatObject();
DistCache.Add("fullCatListObject", returnObj, new TimeSpan(29, 0, 0, 0));
}
return View(returnObj);
}
值得注意的是我们的对象应该序列化例如:
view plaincopy to clipboardprint?
[Serializable]
public class CategoryObject
{
public string CAT_NAME { get; set; }
public int CAT_ID { get; set; }
public int LEVEL { get; set; }
}