惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Security Affairs
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Jina AI
Jina AI
P
Palo Alto Networks Blog
GbyAI
GbyAI
大猫的无限游戏
大猫的无限游戏
A
Arctic Wolf
Hugging Face - Blog
Hugging Face - Blog
小众软件
小众软件
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
Blog — PlanetScale
Blog — PlanetScale
S
Schneier on Security
V
Vulnerabilities – Threatpost
C
Cybersecurity and Infrastructure Security Agency CISA
雷峰网
雷峰网
T
Tenable Blog
人人都是产品经理
人人都是产品经理
T
Tor Project blog
C
Cyber Attacks, Cyber Crime and Cyber Security
AWS News Blog
AWS News Blog
Microsoft Security Blog
Microsoft Security Blog
J
Java Code Geeks
Scott Helme
Scott Helme
SecWiki News
SecWiki News
C
CERT Recently Published Vulnerability Notes
Recorded Future
Recorded Future
I
InfoQ
Security Archives - TechRepublic
Security Archives - TechRepublic
Help Net Security
Help Net Security
Cloudbric
Cloudbric
C
Check Point Blog
Engineering at Meta
Engineering at Meta
TaoSecurity Blog
TaoSecurity Blog
B
Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园_首页
N
News and Events Feed by Topic
云风的 BLOG
云风的 BLOG
MyScale Blog
MyScale Blog
腾讯CDC
量子位
Application and Cybersecurity Blog
Application and Cybersecurity Blog
K
Kaspersky official blog
Vercel News
Vercel News
F
Full Disclosure
T
Troy Hunt's Blog
Forbes - Security
Forbes - Security
S
Security @ Cisco Blogs

博客园 - nestea

Method 'Post' of object 'IOWSPostData' failed(方法'POST'作用于对象'IOWSPostData'时失败) 用Win XP安装盘修复系统文件 手机呼叫流程 XML配置字符串中特殊字符的处理 - nestea - 博客园 关于BackgroundWorker的使用 分布式缓存系统Memcached简介与实践[转] 一些很酷的.Net技巧(转载) sql server中的decimal或者numeric的精度问题 (转载) 使用BackgroundWorker组件进行异步操作编程(转载) 操作DataTable中动态的行,一点收集整理资料。 xml转换成DataTable - nestea - 博客园 预处理命令之条件编译(转) 数字的进制(2进制,8进制,16进制) C#中父窗口和子窗口之间实现控件互操作 (转载) 开放式并发冲突检测的四种方法 MDX 中的重要概念 (MDX) 实用工具-文件夹实时同步工具 (群集服务器拷贝) 用windows 2003建立VPN 连接(转载) - nestea Windows 2003下VPN服务器架设攻略 (转载) - nestea
web应用程序中使用MemcachedClient (转载)
nestea · 2009-07-07 · via 博客园 - nestea

原文地址: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 & IsRemoteCacheAvailableprotected 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
        
    }
}