memcache实战之四:接口编程(分别用asp.net自带的System.Web.Caching,以及分布式缓存MemcachedProviders)来实现缓存接口

image

接口 ICachePolicy.cs

using System;
using System.Collections.Generic;
using System.Text;

namespace My_MemcachedProviders
{
/// <summary>
///
缓存策略接口
/// </summary>
public interface ICachePolicy
{
void Add(string key, object value);
object Get(string key);
void Delete(string key);
void DeleteAll();
//设置过期缓存时间,单位秒,默认是60秒
int DefaultExpireTime { set; get; }
}
}

 

分别实现

一:MemcachedProviders实现


using System;
using System.Collections.Generic;
using System.Web;
using MemcachedProviders.Cache;// 引用类库MemcachedProviders

namespace My_MemcachedProviders
{
    /// <summary>实现了 缓存操作接口的,Memcached Provider操作类
   
///
    /// </summary>
   
public class MemcachedCacheProvidersPolicy:ICachePolicy
   
{


        public void Add(string key, object value)
        {
            DistCache.Add(key, value,new TimeSpan(0,0,DefaultExpireTime));
        }

        public object Get(string key)
        {
            return DistCache.Get(key);
        }

        public void Delete(string key)
        {
            DistCache.Remove(key);
        }

        public void DeleteAll()
        {
            DistCache.RemoveAll();
        }

        //设置缓存的时间
       
public int DefaultExpireTime
        {
            get
           
{
                //默认的缓存时间是在web.config里面设置
               
if (DistCache.DefaultExpireTime==0)
                {
                    DistCache.DefaultExpireTime = 60;
                }
                return Convert.ToInt32(DistCache.DefaultExpireTime);
            }
            set
           
{
                DistCache.DefaultExpireTime = value;
            }
        }
    }
}


二:System.Web.Caching 实现
using
System;
using System.Collections.Generic;
using System.Web;
using System.Collections;
using System.Web.Caching;

namespace My_MemcachedProviders
{
    /// <summary>实现了 缓存操作接口的  HttpRuntime.Cache 操作类
   
///
    /// </summary>
   
public class HttpRuntimeCachePolicy : ICachePolicy
   
{
        private static Cache webCache = null;
        private static int defaultExpireTime = 0;
        public HttpRuntimeCachePolicy()
        {
            if (webCache == null)
            {
                webCache = HttpRuntime.Cache;
            }
        }

        /// <summary>添加/更新缓存(更新缓存会延长缓存的时间)
       
///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
       
public void Add(string key, object value)
        {
            webCache.Insert(key, value, null, DateTime.Now.AddSeconds(DefaultExpireTime), Cache.NoSlidingExpiration);
            //webCache.Insert(key, value, null, DateTime.Now.AddSeconds(DefaultExpireTime), TimeSpan.Zero, CacheItemPriority.Normal, null);
       
}
      
        public object Get(string key)
        {
            return webCache[key];
        }

        public void Delete(string key)
        {
            if (webCache[key] != null)
            {
                webCache.Remove(key);
            }
        }

        //循环所有的缓存,并且删除
       
public void DeleteAll()
        {
            IDictionaryEnumerator CacheEnum = webCache.GetEnumerator();
            ArrayList al = new ArrayList();
            while (CacheEnum.MoveNext())
            {
                al.Add(CacheEnum.Key);
            }
            foreach (string key in al)
            {
                webCache.Remove(key);
            }

        }

        //属性,用来设置缓存的过期时间
       
public int DefaultExpireTime
        {
            get
           
{
                if (defaultExpireTime == 0)
                {
                    defaultExpireTime = 60;
                }
                return defaultExpireTime;
            }
            set
           
{
                defaultExpireTime = value;
            }
        }
    }
}


然后是web.config里面的配置

<?xml version="1.0"?>
<configuration>
    <!--Memcached Providers客户端的配置1  开始-->
    <configSections>
        <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"/>
    </configSections>
    <!--Memcached Providers客户端的配置1  结束-->

    <!--Memcached Providers客户端的配置2  开始-->
    <enyim.com>
        <memcached>
            <servers>
                <!-- put your own server(s) here-->
                <add address="127.0.0.1" port="11211" />
                <!--<add address="127.0.0.1" port="11555" />
                <add address="211.174.120.256" port="11211" />
                <add address="202.96.147.122" port="11211" />-->
            </servers>
            <socketPool minPoolSize="10" maxPoolSize="100" connectionTimeout="00:00:10" deadTimeout="00:02:00" />
        </memcached>
    </enyim.com>

    
    <!--Memcached Providers客户端的配置2  结束-->

    <!--Memcached Providers客户端的配置3  开始-->
    <cacheProvider defaultProvider="MemcachedCacheProvider">
        <providers>
            <add name="MemcachedCacheProvider"
           type="MemcachedProviders.Cache.MemcachedCacheProvider, MemcachedProviders"  keySuffix="_MySuffix_" defaultExpireTime="60"/>
        </providers>
    </cacheProvider>
    <!--Memcached Providers客户端的配置3  结束-->

    <!--Memcached Providers客户端的配置4  开始-->
    <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-ref>
        </root>
    </log4net>

    <!--Memcached Providers客户端的配置4  结束   下面的 都是和 Memcached Providers  配置无关的-->

    <appSettings>
        <!--配置缓存的类名称-->
        <!--<add key="CacheTypeName" value="My_MemcachedProviders.MemcachedCacheProvidersPolicy,My_MemcachedProviders"/>-->
        <add key="CacheTypeName" value="My_MemcachedProviders.HttpRuntimeCachePolicy,My_MemcachedProviders"/>
        <!--配置缓存的类名称结束-->
    </appSettings>
    <connectionStrings />
    <system.web>
        <compilation debug="true">

        </compilation>
        <!--
            通过 <authentication> 节可以配置
            安全身份验证模式,ASP.NET 
            使用该模式来识别来访用户身份。 
        -->
        <authentication mode="Windows" />
        <!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 <customErrors> 节
            可以配置相应的处理步骤。具体而言,
            开发人员通过该节可配置要显示的 html 错误页,
            以代替错误堆栈跟踪。

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->

    </system.web>

</configuration>

最后是前台的测试代码
<%
@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="My_MemcachedProviders._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
    <
title></title>
</
head>
<
body>
    <
form id="form1" runat="server">
    <
div>
   
       
请输入用户ID<asp:TextBox ID="txtId" runat="server"></asp:TextBox>
        <
asp:Button ID="btnSearch" runat="server" Text="搜索" OnClick="Search" />
        <
asp:Literal ID="litType" runat="server"></asp:Literal>
        <
asp:Literal ID="litResult" runat="server"></asp:Literal>
        
        <
br />
       
更新值<asp:TextBox ID="txtNew" runat="server"></asp:TextBox>
        
        <
br />
        <
br />
        <
asp:Button ID="btnClear" runat="server" Text="清空缓存" onclick="btnClear_Click" />
        
    </
div>
    </
form>
</
body>
</
html>


using
System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Configuration; namespace My_MemcachedProviders { public partial class _Default : System.Web.UI.Page { List<Person> listp = new List<Person> { new Person() { Id = "1", Username = "测试数据1" }, new Person() { Id = "2", Username = "测试数据2" }, new Person() { Id = "3", Username = "测试数据3" }, new Person() { Id = "4", Username = "测试数据4" }, new Person() { Id = "5", Username = "测试数据5" }, new Person() { Id = "6", Username = "测试数据6" }, new Person() { Id = "7", Username = "测试数据7" }, }; //ICachePolicy _cache = new MemcachedCacheProvidersPolicy(); //ICachePolicy _cache = new HttpRuntimeCachePolicy(); ICachePolicy _cache = null; protected void Page_Load(object sender, EventArgs e) { string typeName = ConfigurationManager.AppSettings["CacheTypeName"]; _cache= (ICachePolicy)Activator.CreateInstance(Type.GetType(typeName)); } //每次搜索的时候,判断缓存里面有没有这个人,有的话,直接读缓存,没有的话,就增加到缓存 protected void Search(object sender, EventArgs e) { // _cache.DefaultExpireTime = 60; //手动设置缓存为60秒 string id = txtId.Text.Trim(); Person per = null; string newVal = txtNew.Text.Trim(); for (int i = 0; i < listp.Count; i++) { if (listp[i].Id == id) { per = listp[i]; //如果缓存不存在,我们就把person这个实体放进去 if (_cache.Get(per.Id) == null) { _cache.Add(per.Id, per); litType.Text = "从数据库读,并增加到缓存"; litResult.Text = per.Username; } else//如果缓存存在,则判断是不是修改值,如果修改,则先修改实体以及缓存 { litType.Text = "从缓存来读"; if (!string.IsNullOrEmpty(newVal)) { per.Username = newVal; _cache.Add(per.Id, per); txtNew.Text = ""; } Person temp = (Person)_cache.Get(per.Id); litResult.Text = temp.Username; } } } } //清空缓存 protected void btnClear_Click(object sender, EventArgs e) { _cache.DeleteAll(); litType.Text = ""; litResult.Text = "清除所有缓存"; } } }


 

posted @ 2012-12-10 16:00  梨花驿路  阅读(882)  评论(0编辑  收藏  举报