分布式緩存系統(tǒng)memcached簡介與實踐
memcached是什么?
memcached是由Danga Interactive開發(fā)的,高性能的,分布式的內(nèi)存對象緩存系統(tǒng),用于在動態(tài)應用中減少數(shù)據(jù)庫負載,提升訪問速度。
memcached能緩存什么?
通過在內(nèi)存里維護一個統(tǒng)一的巨大的hash表,Memcached能夠用來存儲各種格式的數(shù)據(jù),包括圖像、視頻、文件以及數(shù)據(jù)庫檢索的結果等。
memcached快么?
非常快。memcached使用了libevent(如果可以的話,在linux下使用epoll)來均衡任何數(shù)量的打開鏈接,使用非阻塞的網(wǎng)絡I/O,對內(nèi)部對象實現(xiàn)引用計數(shù)(因此,針對多樣的客戶端,對象可以處在多樣的狀態(tài)), 使用自己的頁塊分配器和哈希表, 因此虛擬內(nèi)存不會產(chǎn)生碎片并且虛擬內(nèi)存分配的時間復雜度可以保證為O(1).。
Danga Interactive為提升Danga Interactive的速度研發(fā)了memcached。目前,LiveJournal.com每天已經(jīng)在向一百萬用戶提供多達兩千萬次的頁面訪問。而這些,是由一個由web服務器和數(shù)據(jù)庫服務器組成的集群完成的。memcached幾乎完全放棄了任何數(shù)據(jù)都從數(shù)據(jù)庫讀取的方式,同時,它還縮短了用戶查看頁面的速度、更好的資源分配方式,以及memcache失效時對數(shù)據(jù)庫的訪問速度。
memcached的特點
memcached的緩存是一種分布式的,可以讓不同主機上的多個用戶同時訪問, 因此解決了共享內(nèi)存只能單機應用的局限,更不會出現(xiàn)使用數(shù)據(jù)庫做類似事情的時候,磁盤開銷和阻塞的發(fā)生。
memcached的使用
memcached服務器端的安裝 (此處將其作為系統(tǒng)服務安裝)
下載文件:memcached 1.2.1 for Win32 binaries (Dec 23, 2006)
1. 解壓縮文件到
c:\memcached
2. 命令行輸入
'c:\memcached\memcached.exe -d install'
3. 命令行輸入
'c:\memcached\memcached.exe -d start'
該命令啟動 memcached ,默認監(jiān)聽端口為 11211,通過 memcached.exe -h 可以查看其幫助。
.NET memcached client library
下載文件:https://sourceforge.net/projects/memcacheddotnet/
里面有.net1.1 和 .net2.0的兩種版本 還有一個不錯的例子。
應用
1. 將Commons.dll,ICSharpCode.SharpZipLib.dll,log4net.dll,Memcached.ClientLibrary.dll 等放到bin目錄
2. 引用Memcached.ClientLibrary.dll
3. 代碼
namespace Memcached.MemcachedBench
{
using System;
using System.Collections;
using Memcached.ClientLibrary;
public class MemcachedBench
{
[STAThread]
public static void Main(String[] args)
{
string[] serverlist = { "10.0.0.131:11211", "10.0.0.132:11211" };
//初始化池
SockIOPool pool = SockIOPool.GetInstance();
pool.SetServers(serverlist);
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();
// 獲得客戶端實例
MemcachedClient mc = new MemcachedClient();
mc.EnableCompression = false;
Console.WriteLine("------------測 試-----------");
mc.Set("test", "my value"); //存儲數(shù)據(jù)到緩存服務器,這里將字符串"my value"緩存,key 是"test"
if (mc.KeyExists("test")) //測試緩存存在key為test的項目
{
Console.WriteLine("test is Exists");
Console.WriteLine(mc.Get("test").ToString()); //在緩存中獲取key為test的項目
}
else
{
Console.WriteLine("test not Exists");
}
Console.ReadLine();
mc.Delete("test"); //移除緩存中key為test的項目
if (mc.KeyExists("test"))
{
Console.WriteLine("test is Exists");
Console.WriteLine(mc.Get("test").ToString());
}
else
{
Console.WriteLine("test not Exists");
}
Console.ReadLine();
SockIOPool.GetInstance().Shutdown(); //關閉池, 關閉sockets
}
}
}
4. 運行結果

【編輯推薦】




























