全面解析windows下Memcache技術應用

來源:互聯網
上載者:User

標籤:

 

一、Memcache介紹

      Memcache 是 danga.com 的一個項目,最早是為 LiveJournal 服務的,目前全世界不少人使用這個快取項目來構建自己大負載的網站,來分擔資料庫的壓力。它可以應對任意多個串連,使用非阻塞的網路 IO 。由於它的工作機制是在記憶體中開闢一塊空間,然後建立一個 HashTable , Memcached 自管理這些 HashTable 。Memcache是高效能的分布式記憶體快取服務器。一般的使用目的是,通過快取資料庫查詢結果,減少資料庫訪問次數,以提高動態Web應用的速度、提高可擴充性。Memcache 官方網站: http://www.danga.com/memcached。

二、Memcache安裝

       安裝包裡面會有x64和x86兩個檔案夾,根據作業系統選擇一個開啟會找到memcached.exe。這個檔案不能直接雙擊運行安裝,需要通過cmd進行安裝。

 

    cmd命令:Memcache –d start|stop|shutdown|restart|uninstall|install 啟動|停止|關閉|重啟|卸載|安裝。

     安裝步驟:1.找到檔案memcache.exe路徑;

                   2.memcache –d install安裝完畢;

 

                   3.啟動服務後windows進程中可以看到memcache.exe;

                  4.伺服器安裝完成後,我們可以通過telnet到伺服器測試一下(如果提示telnet命令不存在,需要去控制台開啟windows的telnet服務功能) 例如:                       10.0.27.120是安裝memcache服務的ip地址,11211是預設的連接埠。輸入stats查看參數資訊。

到此memcache的安裝全部完成。

三、Memcache在程式中的應用

     在解決方案中建立memcache的類庫,引用以下幾個類庫,Commons.dll,Memcached.ClientLibrary.dll,ICSharpCode.SharpZipLib.dll。建立MemcacheHelper.cs這個memcache的使用類。準備工作做完之後開始進入memcache的使用。

1.在web.config裡面配置memcache的伺服器位址

<appSettings>

<!--memcache的伺服器配置,IP地址後期再改,連接埠號碼固定為11211-->
<add key="Memcached.ServerList" value="10.3.2.24:11211"/>

<appSettings>

2.在MemcacheHelper.cs類裡面編寫實現代碼

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using Memcached.ClientLibrary;using System.Data;using System.Configuration;using NLP.Common;namespace NLP.Memcache{    public class MemcacheHelper    {        #region 全域靜態對象        // 全域Socket串連池對象        private static SockIOPool sockIOPool;        public static SockIOPool CurrentPool        {            get            {                return sockIOPool;            }        }        // 全域Memcached用戶端對象        private static MemcachedClient mc;        #endregion        public static bool MemcacheHelperInit()        {            try            {                // 初始化Memcached伺服器列表                string[] serverList = ConfigurationManager.AppSettings["Memcached.ServerList"].Split(‘,‘);                // 初始化Socket串連池                sockIOPool = SockIOPool.GetInstance("MemPool");                sockIOPool.SetServers(serverList);                sockIOPool.Initialize();                // 初始化Memcached用戶端                mc = new MemcachedClient();                mc.PoolName = "MemPool";                mc.EnableCompression = false;                return true;            }            catch (Exception ex)            {                return false;            }        }        /// <summary>        /// 判斷pkey關鍵字是否在Pmc中        /// </summary>        /// <param name="pMC"></param>        /// <param name="pKey"></param>        /// <returns></returns>        public static bool IsCache(string pKey)        {            if (MemcacheHelperInit())            {                if (mc.KeyExists(pKey))                {                    return true;                }                else                {                    return false;                }            }            else            {                return false;            }        }        /// <summary>        /// 刪掉Memcache 資料        /// </summary>        /// <param name="key"> </param>        /// <returns></returns>        public static bool RemoveCache(string pKey)        {            if (MemcacheHelperInit())            {                if (!mc.KeyExists(pKey))                {                    return false;                }                else                {                    return mc.Delete(pKey);                }            }            else            {                return false;            }        }        /// <summary>        /// Set-新增或修改        /// </summary>        /// <param name="key">鍵</param>        /// <param name="value">值</param>        /// <returns>是否成功</returns>        public static bool AddCache(string key, object value)        {            if (MemcacheHelperInit())            {                if (!mc.KeyExists(key))                {                    return mc.Add(key, value);                }                else                {                    return mc.Set(key, value);                }            }            else            {                return false;            }        }        /// <summary>        /// Set-新增或修改        /// </summary>        /// <param name="key">鍵</param>        /// <param name="value">值</param>        /// <param name="expiry">到期時間</param>        /// <returns>是否成功</returns>        public static bool AddCache(string key, object value, DateTime expiry)        {            if (MemcacheHelperInit())            {                if (!mc.KeyExists(key))                {                    return mc.Add(key, value, expiry);                }                else                {                    return mc.Set(key, value, expiry);                }            }            else            {                return false;            }        }        /// <summary>        /// 根據單個key值擷取Memcache 資料        /// </summary>        /// <param name="key"></param>        /// <returns></returns>        public static object GetCache(string key)        {            if (MemcacheHelperInit())            {                if (!mc.KeyExists(key))                {                    return null;                }                else                {                    return mc.Get(key);                }            }            else            {                return false;            }        }        /// <summary>        /// 根據多個key值擷取Memcache 資料        /// </summary>        /// <param name="key"> </param>        /// <returns></returns>        public static Dictionary<string, object> GetCache(string[] keys)        {            Dictionary<string, object> dic = new Dictionary<string, object>();            if (MemcacheHelperInit())            {                foreach (string key in keys)                {                    object obj = mc.Get(key);                    if (!dic.ContainsKey(key) && obj != null)                        dic.Add(key, obj);                }                return dic;            }            else            {                return null;            }        }    }}
View Code

3.在調用代碼裡面調用MemcacheHelper.cs的memcache方法

如bool result=MemcacheHelper.AddCache("User","123456");//實現新增key位User,value值為123456的memcache

//擷取memcache中value值,為json格式
string ob_json = MemcacheHelper.GetCache("User").ToString();

這樣就實現了memcache的新增、查詢的完整應用。

全面解析windows下Memcache技術應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.