Windows上memcached的使用


Memcached是什么?
Memcached是由Danga Interactive開發的,高性能的,分布式的內存對象緩存系統,用於在動態應用中減少數據庫負載,提升訪問速度。

Memcached能緩存什么?
通過在內存里維護一個統一的巨大的hash表,Memcached能夠用來存儲各種格式的數據,包括圖像、視頻、文件以及數據庫檢索的結果等。
Memcached快么?
非常快。Memcached使用了libevent(如果可以的話,在linux下使用epoll)來均衡任何數量的打開鏈接,使用非阻塞的網絡I/O,對內部對象實現引用計數(因此,針對多樣的客戶端,對象可以處在多樣的狀態), 使用自己的頁塊分配器和哈希表, 因此虛擬內存不會產生碎片並且虛擬內存分配的時間復雜度可以保證為O(1).。
Memcached的特點?
Memcached的緩存是一種分布式的,可以讓不同主機上的多個用戶同時訪問, 因此解決了共享內存只能單機應用的局限,更不會出現使用數據庫做類似事情的時候,磁盤開銷和阻塞的發生。

Memcached的使用需要服務端和客戶端同時合作完成。

服務端一般用Danga Interactive開發的:

Memcached官方站點:http://www.danga.com/memcached/

Memcached Win32 1.2.6下載:http://code.jellycan.com/memcached/ 或者 http://code.google.com/p/beitmemcached/(windows)

1.解壓Memcached_1.2.5.zip ,它是memcached的服務器端。
2.把Memcached_1.2.5復制到你指定的做為緩存服務器的電腦上,比如叫做192.168.0.1。
3.cmd下運行類似命令 'd:/memcached/memcached.exe -d install' 安裝服務器端,這時候它應該會出現在windows服務中
4.cmd下運行類似命令 'd:/memcached/memcached.exe -d start'啟動服務,看服務器進程中是否有memcached進程。
5.確認服務器端口11211是否開放(防火牆設置中),否則其他機器無法訪問
6.服務器端這時已經安裝完畢、在其他機器上測試一下,cmd輸入telnet 192.168.0.1 11211看能否登錄

telnet添加數據到memcached:

add key 0 時間(長度(存放多長時間由你指定, 鍵名不能重復,但是值可以重復

)例:add name 0 5 5不可以在add name 0 77 44

獲取數據

get key值  【key-val   key不能重復,但是val可以重復】

修改數據

replace key值 0 60 5 【如果key值不存在,則失敗】

set key值 0 60 5  【如果key值不存在,相當於添加,如果存在,則相當於修改.】

刪除數據

delete 鍵值

例:

至此服務端配置完成

客戶端的版本比較多,並且不能互用,因為采用了壓縮機制,日志等功能,所以在選擇客戶端時要注意這些。

Memcached .NET客戶端:

1).NET memcached client library

  下載地址:https://sourceforge.net/projects/memcacheddotnet

2)enyim.com Memcached Client

  下載地址:http://www.codeplex.com/EnyimMemcached/

3)Memcached Providers

  下載地址:http://www.codeplex.com/memcachedproviders

4) BeIT Memcached

  下載地址:http://code.google.com/p/beitmemcached/

我這里用BeIT,BeITMemcached_source_2008_05_31.zip壓縮包下栽下來,里面有Sample

class Example {
        public static void Main(string[] args) {
            //---------------------
            // Setting up a client.
            //---------------------
            Console.Out.WriteLine("Setting up Memcached Client.");
            MemcachedClient.Setup("MyCache", new string[] { "localhost" });

            //It is possible to have several clients with different configurations:
            //If it is impossible to resolve the hosts, this method will throw an exception.
            try {
                MemcachedClient.Setup("MyOtherCache", new string[]{ "server1.example.com:12345", "server2.example.com:12345"});
            } catch (Exception e) {
                Console.WriteLine(e.Message);
            }

            //Get the instance we just set up so we can use it. You can either store this reference yourself in
            //some field, or fetch it every time you need it, it doesn't really matter.
            MemcachedClient cache = MemcachedClient.GetInstance("MyCache");

            //It is also possible to set up clients in the standard config file. Check the section "beitmemcached" 
            //in the App.config file in this project and you will see that a client called "MyConfigFileCache" is defined.
            MemcachedClient configFileCache = MemcachedClient.GetInstance("MyConfigFileCache");

            //Change client settings to values other than the default like this:
            cache.SendReceiveTimeout = 5000;
            cache.ConnectTimeout = 5000;
            cache.MinPoolSize = 1;
            cache.MaxPoolSize = 5;

            //----------------
            // Using a client.
            //----------------

            //Set some items
            Console.Out.WriteLine("Storing some items.");
            cache.Set("mystring", "The quick brown fox jumped over the lazy dog.");
            cache.Set("myarray", new string[]{"This is the first string.", "This is the second string."});
            cache.Set("myinteger", 4711);
            cache.Set("mydate", new DateTime(2008, 02, 23));
            //Use custom hash
            cache.Set("secondstring", "Flygande b鋍kasiner s鰇a hwila p?mjuka tufvor", 4711);

            //Get a string
            string str = cache.Get("mystring") as string;
            if (str != null) {
                Console.Out.WriteLine("Fetched item with key: mystring, value: " + str);
            }

            //Get an object
            string[] array = cache.Get("myarray") as string[];
            if (array != null) {
                Console.Out.WriteLine("Fetched items with key: myarray, value 1: " + array[0] + ", value 2: " + array[1]);
            }

            //Get several values at once
            object[] result = cache.Get(new string[]{"myinteger", "mydate"});
            if (result[0] != null && result[0] is int) {
                Console.Out.WriteLine("Fetched item with key: myinteger, value: " + (int)result[0]);
            }
            if (result[1] != null && result[1] is DateTime) {
                Console.Out.WriteLine("Fetched item with key: mydate, value: " + (DateTime)result[1]);
            }

            str = cache.Get("secondstring", 4711) as string;
            if (str != null) {
                Console.Out.WriteLine("Fetched item with key and custom hash: secondstring, value: " + str);
            }

            //Set a counter
            Console.Out.WriteLine("Setting an item for incrementing and decrementing.");
            cache.SetCounter("mycounter", 9000);
            ulong? counter = cache.GetCounter("mycounter");
            if (counter.HasValue) {
                Console.Out.WriteLine("Fetched mycounter, value: " + counter.Value);
            }

            //Increment the counter
            counter = cache.Increment("mycounter", 1);
            if (counter.HasValue) {
                Console.Out.WriteLine("Incremented mycounter with 1, new value: " + counter.Value);
            }

            //Decrement the counter
            counter = cache.Decrement("mycounter", 9000);
            if (counter.HasValue) {
                Console.Out.WriteLine("Decremented mycounter with 9000, new value: " + counter.Value);
            }

            //Append and prepend
            Console.Out.WriteLine("Storing bar for append/prepend");
            cache.Set("foo", "bar");
            Console.Out.WriteLine("Appending baz");
            cache.Append("foo", " baz");
            Console.Out.WriteLine("Prepending foo");
            cache.Prepend("foo", "foo ");
            Console.Out.WriteLine("New value: " + cache.Get("foo"));

            //Cas
            cache.Delete("castest");
            Console.Out.WriteLine("Trying to CAS non-existant key castest: " + cache.CheckAndSet("castest", "a", 0));
            Console.Out.WriteLine("Setting value for key: castest, value: a");
            cache.Set("castest", "a");
            Console.Out.WriteLine("Trying to CAS key castest with the wrong unique: " + cache.CheckAndSet("castest", "a", 0));
            ulong unique;
            cache.Gets("castest", out unique);
            Console.Out.WriteLine("Getting cas unique for key castest: " + unique);
            Console.Out.WriteLine("Trying to CAS again with the above unique: " + cache.CheckAndSet("castest", "b", unique));
            string value = cache.Gets("castest", out unique) as string;
            Console.Out.WriteLine("New value: " + value + ", new unique: " + unique);

            Console.Out.WriteLine("Displaying the socketpool status:");
            foreach (KeyValuePair<string, Dictionary<string, string>> host in cache.Status()) {
                Console.Out.WriteLine("Host: " + host.Key);
                foreach (KeyValuePair<string, string> item in host.Value) {
                    Console.Out.WriteLine("\t" + item.Key + ": " + item.Value);
                }
                Console.Out.WriteLine();
            }

            Console.Out.WriteLine();
            Console.Out.WriteLine("Finished. Press enter to exit.");
            Console.In.ReadLine();
        }
    }

最早的客戶端是采用取余的hash算法來查找服務器的,我們知道以往資料要放到 M 台服務器上,最簡單的方法就是取余數 (hash_value % M) 然后放到對應的服務器上,那就是當添加或移除服務器時,緩存重組的代價相當巨大。添加服務器后,余數就會產生巨變,這樣就無法獲取與保存時相同的服務器, 從而影響緩存的命中率。
如今采用了Consistent Hashing算法來改善性能,具體可以看最后的參考網址。

參考

http://blog.csdn.net/jinjazz/article/details/2664136

http://www.cnblogs.com/dudu/archive/2009/07/19/1526407.html

http://www.cnblogs.com/mecity/archive/2011/06/13/2079548.html

http://www.cnblogs.com/wucg/archive/2011/03/01/1968185.html

http://blog.csdn.net/whjwhja6/article/details/9172463

http://blog.csdn.net/hguisu/article/details/7353551

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM