asp.net mvc3.0 整合memcached

來源:互聯網
上載者:User

     
        memcached 的強大,不用說了!我這裡對它的應用也只是冰山一角。都是些基本運用.

       可以先從  memcached官方 下載 。最新版本應該是1.4.15。我這裡下載的是windows穩定版 版本是1.4.14.

        下載下來後.直接解壓然後將memcached裡面檔案拷貝到你想建立的目錄下即可

           

       

        

    然後dos下安裝一下就OK了!至於一些基本參數可以再dos中設定,也可以再項目中設定,比如最大串連數,最小串連數,逾時時間等等.(我的虛擬機器又不工作了!FK.具體參數設定就不說了!)。參數資訊可以參考一下下面我在網上找的一個列表.

         -p 監聽的連接埠

         -l 串連的IP地址, 預設是本機

         -d start 啟動memcached服務

         -d restart 重起memcached服務

         -d stop|shutdown 關閉正在啟動並執行memcached服務

         -d install 安裝memcached服務

         -d uninstall 卸載memcached服務

         -u 以的身份運行 (僅在以root啟動並執行時候有效)

         -m 最大記憶體使用量,單位MB。預設64MB

         -M 記憶體耗盡時返回錯誤,而不是刪除項

         -c 最大同時串連數,預設是1024

         -f 塊大小增長因子,預設是1.25

         -n 最小分配空間,key+value+flags預設是48

         -h 顯示協助

         mvc3.0項目搭建好後,會自動產生Global.asax檔案,項目的一個通用檔案! 我們在這裡面設定memcached 的啟動參數!

        

        public static void cachePool()        {            string poolname = "default";            String[] serverlist = { "127.0.0.1:11211" };          ->這裡如果需要部署分布式, 繼續在後面追加ip即可!例如String[] serverlist = { "192.168.1.1:11211","192.168.1.2:11211" };            SockIOPool pool = SockIOPool.GetInstance(poolname);            pool.SetServers(serverlist); //設定伺服器列表            //各伺服器之間負載平衡的設定            pool.SetWeights(new int[] { 1 });                  ->這裡部署分布式的時候是個很重要的參數,  相當於設定cache 值的主次!            //socket pool設定            pool.InitConnections = 5; //初始化時建立的串連數            pool.MinConnections = 5; //最小串連數            pool.MaxConnections = 2000; //最大串連數            //串連的最大空閑時間,下面設定為6個小時(單位ms),超過這個設定時間,串連會被釋放掉            pool.MaxIdle = 1000 * 60 * 60 * 6;            //通訊的逾時時間,下面設定為3秒(單位ms),.NET版本沒有實現            pool.SocketTimeout = 1000 * 3;            //socket串連的逾時時間,下面設定表示串連不逾時,即一直保持串連狀態            pool.SocketConnectTimeout = 0;            pool.Nagle = false; //是否對TCP/IP通訊使用Nalgle演算法,.NET版本沒有實現            //維護線程的間隔啟用時間,下面設定為60秒(單位s),設定為0表示不啟用維護線程            pool.MaintenanceSleep = 60;            //socket單次任務的最大時間,超過這個時間socket會被強行中斷掉(當前任務失敗)            pool.MaxBusy = 1000 * 10;            pool.Failover = true;            pool.Initialize();        }        protected void Application_Start()      //這裡調用        {                         cachePool();        }

            

                OK,基本設定已經完成,下一步 我們需要下載兩個dll 。用於整合net。 一個是Memcached.ClientLibrary 還有 MemcachedProviders.然後引用一下!

               

                 接下來我們寫一個cache的操作類DataCache

                 

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using Memcached.ClientLibrary;using System.Security.Cryptography;namespace Common{    /// <summary>    /// memcached 快取作業類    /// </summary>     public class DataCache    {        public static void SetMc(object obj, string cacheName)        {            string poolname = "default";            cacheName = GetMD5(cacheName);             //用戶端執行個體            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();            mc.PoolName = poolname; //如果執行個體化pool時沒有poolname,該行可以不用。            mc.EnableCompression = true;            mc.CompressionThreshold = 10240;            if (obj != null)                mc.Set(cacheName, obj, DateTime.Now.AddHours(3));        }        public static void SetMc(object obj, string cacheName, int minutes)        {            string poolname = "default";            cacheName = GetMD5(cacheName);            //用戶端執行個體            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();            mc.PoolName = poolname; //如果執行個體化pool時沒有poolname,該行可以不用。            mc.CompressionThreshold = 10240;            if (obj != null)                mc.Set(cacheName, obj, DateTime.Now.AddMinutes(minutes));        }        public static object GetMc(string cacheName)        {            string poolname = "default";            cacheName = GetMD5(cacheName);            //用戶端執行個體            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();            mc.PoolName = poolname; //如果執行個體化pool時沒有poolname,該行可以不用。            mc.EnableCompression = true;            return (object)mc.Get(cacheName);        }        public static void UpdateMc(object obj, string cacheName)        {            string poolname = "default";            cacheName = GetMD5(cacheName);            //用戶端執行個體            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();            mc.PoolName = poolname; //如果執行個體化pool時沒有poolname,該行可以不用。            mc.Delete(cacheName);            if (obj != null)            {                mc.EnableCompression = true;                mc.Set(cacheName, obj);            }        }        public static void DelMc(string cacheName)        {            string poolname = "default";            cacheName = GetMD5(cacheName);            //用戶端執行個體            MemcachedClient mc = new Memcached.ClientLibrary.MemcachedClient();            mc.PoolName = poolname; //如果執行個體化pool時沒有poolname,該行可以不用。            mc.Delete(cacheName);        }         /// <summary>         /// Cache MD5         /// </summary>         /// <param name="str"></param>         /// <returns></returns>        public static string GetMD5(string str)        {            int size = Common.PageBase.memcachedMD5Size;            if (size == 16)            {//16位                MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();                str = BitConverter.ToString(md5.ComputeHash(System.Text.UTF8Encoding.Default.GetBytes(str)), 4, 8);                str = str.Replace("-", "");            }            else            {  //32位                byte[] b = System.Text.Encoding.Default.GetBytes(str);                b = new MD5CryptoServiceProvider().ComputeHash(b);                for (int i = 0; i < b.Length; i++)                {                    str += b[i].ToString("x").PadLeft(2, '0');                }            }            return str;        }    }}

                    OK. 可以看到這兩個參數。是設定memcached緩衝的壓縮比。memcached的單個item最多儲存1m資料。 

            mc.EnableCompression = true;

                    至於cache  key 用md5加密,有兩個原因,1是因為memcached 對於key的長度也是有限制,如果超出限制長度當前這個item會一直處於失效狀態,2是因為安全問題。

                      

                    基本設定都已經完成,接下來可以使用我們的DataCache 進行資料緩衝了。

                   

        /// <summary>        /// get Model  by code        /// </summary>        /// <param name="OrderCode"></param>        /// <returns></returns>        public OrderInfo OrderInfoModelByOrderCode(string OrderCode)        {            string cacheKey = "OrderInfoModelByOrderCode_" + OrderCode;            object objModel = Common.DataCache.GetMc(cacheKey);            if (objModel == null)            {                try                {                    OrderInfo orderModel = dal.OrderInfoModelByOrderCode(OrderCode);                    objModel = orderModel;                    if (objModel != null)                    {                        int cacheTime = Common.PageBase.memcachedTime;            //memcached自動逾時時間,比如設定10.當前這個cache item 就會在10分鐘後自動失效,如有新請求,則重新add                        Common.DataCache.SetMc(objModel, cacheKey, cacheTime);                    }                }                catch (Exception ex)                {                }            }            return (OrderInfo)objModel;        }

       到這裡,基本運用就完成了。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.