在web应用程序中使用MemcachedClient

本文来自:http://www.cnblogs.com/yukaizhao/archive/2008/11/10/memcached_client_usage.html

 

一. 背景:

在大访问量的web程序开发中,数据库常常会称为性能的瓶颈。为了缓解数据库的压力,我们频繁的使用缓存,而asp.net自带的Cache很强大,但是有先天的不足,它是进程内的缓存,当站点由多台服务器负载均衡时,当缓存在有数据更新时,我们不能同时将更新后的数据同步到两台或多台web server上。所幸的是老外的大牛开发了memcached分布式缓存,它的性能非凡,memcached常用的.net的client类库有两个分别是:http://code.google.com/p/beitmemcached/http://sourceforge.net/projects/memcacheddotnet/,我个人推荐使用后一个。

有关memcached的介绍和在控制台中的简单调用请参考:分布式缓存系统Memcached简介与实践

二. 如何使用

  1. 安装memcached server端,下载dot net版本的客户端,请参考分布式缓存系统Memcached简介与实践
  2. 在asp.net项目中使用memcached客户端访问服务端
    思路:
    1) 我们在站点启动时即启动memcached的client端,在站点停止时停掉client端,释放占用的端口资源;
    这一点只要把启动和关闭放到Global的Application_Start和Application_End中执行,即可。由于整个网站的运行期间,我们都希望不需要再重新生成MemcachedClient类的实例,所以我们在Global中声明了一个静态的实例来存放此Client。并用一个public的属性RemoteCache和IsRemoteCacheAvailable来暴露MemcachedClient的引用和其是否可用。
    2) 为了方便使用我们需要建一个System.Web.UI.Page类的基类PageBase,在此基类中引用Memcached client的客户端访问类实例,然后新建的所有aspx页面的基类继承PageBase就可以了。
    这儿也很容已做到,我们只需找到 Global appInstance = HttpContext.Current.ApplicationInstance as Global;然后引用Global中暴露的两个属性即可。需要注意的是在程序中引用Global是通过HttpContext.Current.ApplicationInstance而不是HttpContext.Current.Applicatioin,后者只是一个键值对的集合,而前者是网站的HttpApplication的实例

请参考Global和PageBase的代码:


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;

using Memcached.ClientLibrary;
using log4net;

namespace Forum.UI
{
    public class Global : System.Web.HttpApplication
    {
        protected static ILog AppLog = LogManager.GetLogger(typeof(Global));

        public override void Init()
        {
            this.Error += new EventHandler(Application_Error);
            base.Init();
        }


        protected void Application_Error(object sender, EventArgs e)
        {
#if !DEBUG
            Exception ex = Server.GetLastError();
            AppLog.Error(ex.Message, ex);
            Server.ClearError();
            Response.Redirect("~/error/500.htm", true);
#endif
        }

        protected void Application_Start(object sender, EventArgs e)
        {
            SetupMemcachedClient();
        }

        protected void Application_End(object sender, EventArgs e)
        {
            ShutdownMemecachedClient();
        }


        #region RemoteCache
        private static MemcachedClient mc = null;
        private const string MEMCACHED_INSTANCE_NAME = "Memcached-Forum";


        /// <summary>
        /// 返回MemcachedClient是否可用
        /// </summary>
        public bool IsRemoteCacheAvailable
        {
            get
            {
                return mc != null;
            }
        }


        /// <summary>
        /// 外部访问入口
        /// </summary>
        public MemcachedClient RemoteCache
        {
            get
            {
                return mc;
            }
        }

        /// <summary>
        /// 关闭占用的tcp端口资源
        /// </summary>
        private void ShutdownMemecachedClient()
        {
            SockIOPool pool = SockIOPool.GetInstance(MEMCACHED_INSTANCE_NAME);
            if (pool != null) pool.Shutdown();
        }

        /// <summary>
        /// 启动memcachedClient,给client赋予指定参数
        /// </summary>
        private void SetupMemcachedClient()
        {
            string memcachedServers = ConfigurationManager.AppSettings["memcachedServers"];
            string[] servers = memcachedServers.Split(‘;‘);
            SockIOPool pool = SockIOPool.GetInstance(MEMCACHED_INSTANCE_NAME);
            pool.SetServers(servers);

            pool.InitConnections = 3;
            pool.MinConnections = 3;
            pool.MaxConnections = 5;

            pool.SocketConnectTimeout = 1000;
            pool.SocketTimeout = 3000;

            pool.MaintenanceSleep = 30;
            pool.Failover = true;

            pool.Nagle = false;
            pool.Initialize();

            mc = new MemcachedClient();
            mc.PoolName = MEMCACHED_INSTANCE_NAME;
            mc.EnableCompression = false;
        }
        #endregion


    }
}

 


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Web.Caching;
using Memcached.ClientLibrary;
using System.Collections.Generic;

using log4net;
using Forum.Models;
using Forum.UI.Proxy;

namespace Forum.UI
{
    public class PageBase : Page
    {
        #region RemoteCache & IsRemoteCacheAvailable

        protected MemcachedClient RemoteCache
        {
            get
            {
                if (HttpContext.Current.ApplicationInstance == null) return null;
                Global appInstance = HttpContext.Current.ApplicationInstance as Global;
                if (appInstance == null) return null;

                return appInstance.RemoteCache;
            }
        }

        protected bool IsRemoteCacheAvailable
        {
            get
            {
                return RemoteCache != null;
            }
        }
        #endregion
        
    }
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。