标签:style blog http io color ar 使用 for sp
本文来自: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简介与实践
二. 如何使用
请参考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

}
}
标签:style blog http io color ar 使用 for sp
原文地址:http://www.cnblogs.com/zhouyunbaosujina/p/4079550.html