看过网上很多人写过对于memcache的用法,但是总感觉写的不是太详细,更多者是互相转载,很多文章过于类同。下面是自己总结的一点memcache的一点使用经验,不足之处望指出,共同学习~。^_^

=========================================================================

1.相关工具的下载。

  • memcached-1.2.6-win32-bin.zip     MemCached服务端程序(for win,不安装也是可以的,但是不安装的话就不方便我们对缓存到内存中cache的管理,所以建议安装上)
  • Memcached .NET client Library         C#/.NET memcached 客户端dll(在项目中需要添加对该文件的dll的引用,位置【memcacheddotnet\trunk\clientlib\src\clientlib\bin\2.0\Release \】)

2.程序代码(C#)

<1>首先把memcacheddotnet\trunk\clientlib\src\clientlib\bin\2.0\Release \目录下的Commons.dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll复制到bin目录下,然后在项目中添加对这几个dll的引用。

<2>代码模块。

首先添加对memcache的引用,代码如下:

using Memcached.ClientLibrary;

//数据列表绑定方法

private void Bind()
    {
        int count = 0;
        DataSet ds = null;
        CachePoolInitialized();
        string memCache_list = DqId +"_"+page+"_memcache_list";//列表key
        string memCache_count = DqId + "_" + page + "_memcache_count";//数量key
        MemcachedClient mc = new MemcachedClient();
        mc.EnableCompression = false;
        bool exist = mc.KeyExists(memCache_list);//首先判断该key是否存在
        bool exist2 = mc.KeyExists(memCache_count);//首先判断该key是否存在
        if (exist)
        {
            ds = (DataSet)mc.Get(memCache_list);
        }
        else
        {
            ds = dal.GetCJList(DqId, FlId, start, pageSize);
            mc.Set(memCache_list, ds, DateTime.Now.AddSeconds(300));//设置cache
        }
        if (exist2)
        {
            count = Convert.ToInt32(mc.Get(memCache_count));//获取cache
        }
        else
        {
            dal.GetCJCount(DqId, FlId, out count);//获取cache
            mc.Set(memCache_count, count, DateTime.Now.AddSeconds(300));//设置cache
        }
        Literal1.Text = GetPageNum(ds.Tables[0], count, RepLink, pageSize);//自定义的分页方法
        RepLink.DataSource = ds;
        RepLink.DataBind();
    }

//创建memCache的实例

 protected void CachePoolInitialized()
    {
        SockIOPool pool = SockIOPool.GetInstance("default");
        if (!pool.Initialized)
        {
            string[] serverlist = { "192.168.1.107:11211" };//cache存放的服务器,这里可以填写多个,然后设定权重,在这里不做详细的解释
            pool.SetServers(serverlist);

            pool.InitConnections = 3;//初始化连接数

            pool.MinConnections = 3;//最少链接数

            pool.MaxConnections = 5;//最大连接数

            pool.SocketConnectTimeout = 1000;//socket链接超时时间

            pool.SocketTimeout = 3000;//socket超时时间

            pool.MaintenanceSleep = 30;//维护线程休息时间

            pool.Failover = true;//失效转移(一种备份操作模式)

            pool.Nagle = false;//是否用nagle算法启动socket

            pool.Initialize();

       }
    }

==============================================================================

webconfig配置 

<?xml version="1.0"?>
<configuration>
 <configSections>
  <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
   <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
     <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere"/>
     <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
     <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
     <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
     <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
    </sectionGroup>
    
   </sectionGroup>
  </sectionGroup>
 </configSections>

 <appSettings>
  <log4net>
   <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="LogFiles/"/>
    <param name="AppendToFile" value="true"/>
    <param name="MaxSizeRollBackups" value="10"/>
    <param name="StaticLogFileName" value="false"/>
    <param name="DatePattern" value="yyyy-MM-dd&quot;.txt&quot;"/>
    <param name="RollingStyle" value="Date"/>
    <layout type="log4net.Layout.PatternLayout">
     <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger %ndc - %message%newline"/>
    </layout>
   </appender>
   <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
     <param name="ConversionPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger %ndc - %message%newline" />
    </layout>
   </appender>
   <root>
    <level value="ALL" />
    <appender-ref ref="RollingLogFileAppender" />
    <appender-ref ref="ConsoleAppender" />
   </root>
   <logger name="Memcached.ClientLibrary">
    <level value="WARN" />

   </logger>
  </log4net>
  <add key="connectionstring" value="server=192.168.1.107;database=qd8;UID=sa;PWD=pwd"/>
 </appSettings>
 <connectionStrings/>
 <system.web>
  
  <!--
            设置 compilation debug="true" 可将调试符号插入
            已编译的页面中。但由于这会
            影响性能,因此只在开发过程中将此值
            设置为 true。
        -->
  <compilation debug="true">
   <assemblies>
    <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
    <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
   </assemblies>
  </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>
        -->
  <pages>
   <controls>
    <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
    <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   </controls>
  </pages>
  <httpHandlers>
   <remove verb="*" path="*.asmx"/>
   <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
  </httpHandlers>
  <httpModules>
   <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </httpModules>
 </system.web>
 
 <system.codedom>
  <compilers>
   <compiler language="c#;cs;csharp" extension=".cs" warningLevel="4" type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
    <providerOption name="CompilerVersion" value="v3.5"/>
    <providerOption name="WarnAsError" value="false"/>
   </compiler>
  </compilers>
 </system.codedom>
 <!--
        在 Internet 信息服务 7.0 下运行 ASP.NET AJAX 需要 system.webServer
        节。对早期版本的 IIS 来说则不需要此节。
    -->
 <system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules>
   <remove name="ScriptModule"/>
   <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </modules>
  <handlers>
   <remove name="WebServiceHandlerFactory-Integrated"/>
   <remove name="ScriptHandlerFactory"/>
   <remove name="ScriptHandlerFactoryAppServices"/>
   <remove name="ScriptResource"/>
   <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
   <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
  </handlers>
 </system.webServer>
 <runtime>
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
   <dependentAssembly>
    <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
   </dependentAssembly>
   <dependentAssembly>
    <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
   </dependentAssembly>
  </assemblyBinding>
 </runtime>
 
</configuration>
 

==============================================================================

在真正的使用过程中,我们还需根据自己的事情情况来对memcache进行设置和调优。略过~~