在web应用程序中使用MemcachedClient

一. 背景:

在大访问量的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的代码:

ContractedBlock.gif ExpandedBlockStart.gif Global
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
ExpandedBlockStart.gifContractedBlock.gif
{
    
public class Global : System.Web.HttpApplication
ExpandedSubBlockStart.gifContractedSubBlock.gif    
{
        
protected static ILog AppLog = LogManager.GetLogger(typeof(Global));

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



        
protected void Application_Error(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
#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)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            SetupMemcachedClient();
        }


        
protected void Application_End(object sender, EventArgs e)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            ShutdownMemecachedClient();
        }



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


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 返回MemcachedClient是否可用
        
/// </summary>

        public bool IsRemoteCacheAvailable
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return mc != null;
            }

        }



ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 外部访问入口
        
/// </summary>

        public MemcachedClient RemoteCache
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
get
ExpandedSubBlockStart.gifContractedSubBlock.gif            
{
                
return mc;
            }

        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 关闭占用的tcp端口资源
        
/// </summary>

        private void ShutdownMemecachedClient()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            SockIOPool pool 
= SockIOPool.GetInstance(MEMCACHED_INSTANCE_NAME);
            
if (pool != null) pool.Shutdown();
        }


ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
        
/// 启动memcachedClient,给client赋予指定参数
        
/// </summary>

        private void SetupMemcachedClient()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
{
            
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



    }

}

 

ContractedBlock.gif ExpandedBlockStart.gif PageBase
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 == nullreturn null;
                Global appInstance 
= HttpContext.Current.ApplicationInstance as Global;
                
if (appInstance == nullreturn null;

                
return appInstance.RemoteCache;
            }
        }

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

 

三. 后记

仅仅是个人使用心得,如果有问题,请回复讨论。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值