天天看點

C# 操作Memcached

C# 操作Memcached

環境 c# vs2013 ,要在nuget裡引用(安裝) EnyimMemcached ,下面是以調用阿裡雲的ocs(memcached)服務為例

using System;
using Enyim.Caching;


namespace MemcacheTest
{
    /// <summary>
    /// MemcachedClient 幫組類 對外提供接口方法
    /// </summary>
    public class MemcachedHelper
    {
        /// <summary>
        /// 定義一個靜态MemcachedClient用戶端,它随類一起加載,所有對象共用
        /// </summary>
        private static MemcachedClient mclient;
        /// <summary>
        /// 靜态構造函數,初始化Memcached用戶端
        /// </summary>
        static MemcachedHelper()
        {
            mclient = MemCached.getInstance();
        }
        /// <summary>
        /// 向Memcached緩存中添加一條資料
        /// </summary>
        /// <param name="groupName">組名,用來區分不同的服務或應用場景</param>
        /// <param name="key">鍵</param>
        /// <param name="value">值</param>
        /// <param name="expiry">過期時間</param>
        /// <returns>傳回是否添加成功</returns>
        public static bool SetValue(string groupName,string key, object value, DateTime expiry)
        {
            key = groupName + "-" + key;
            return mclient.Store(Enyim.Caching.Memcached.StoreMode.Set,key, value, expiry);
        }
        /// <summary>
        /// 向Memcached緩存中添加一條資料 預設逾時24小時
        /// </summary>
        /// <param name="groupName">組名,用來區分不同的服務或應用場景</param>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool SetValue(string groupName, string key, object value)
        {
            key = groupName + "-" + key;
            return mclient.Store(Enyim.Caching.Memcached.StoreMode.Set, key, value, DateTime.Now.AddHours(24));
        }
        /// <summary>
        /// 通過key 來得到一個對象
        /// </summary>
        /// <param name="groupName">組名,用來區分不同的服務或應用場景</param>
        /// <param name="key">鍵</param>
        /// <returns>對象</returns>
        public static object GetValue(string groupName, string key)
        {
            key = groupName + "-" + key;
            return mclient.Get(key);
        }
        /// <summary>
        /// 通過key 來得到一個對象(前類型)
        /// </summary>
        /// <typeparam name="T">類型</typeparam>
        /// <param name="groupName">組名,用來區分不同的服務或應用場景</param>
        /// <param name="key">鍵</param>
        /// <returns></returns>
        public static T GetValue<T>(string groupName, string key)
        {
            key = groupName + "-" + key;
            return mclient.Get<T>(key);
        }
        /// <summary>
        /// 清除指定key的cache
        /// </summary>
        /// <param name="groupName">組名,用來區分不同的服務或應用場景</param>
        /// <param name="key">鍵</param>
        /// <returns></returns>
        public static bool Remove(string groupName, string key)
        {
            key = groupName + "-" + key;
            return mclient.Remove(key);
        }
        /// <summary>
        /// 清除所有cache
        /// </summary>
        public static void RemoveAll()
        {
             mclient.FlushAll();
        }
    }
}      
using System.Net;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;


namespace MemcacheTest
{
    /// <summary>
    /// MemcachedClient 配置類
    /// </summary>
    public sealed class MemCached
    {
        private static MemcachedClient MemClient;
        static readonly object padlock = new object();
        //線程安全的單例模式
        public static MemcachedClient getInstance()
        {
            if (MemClient == null)
            {
                lock (padlock)
                {
                    if (MemClient == null)
                    {
                        MemClientInit();
                    }
                }
            }
            return MemClient;
        }
        static void MemClientInit()
        {
            //初始化緩存
            MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();
            IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry("XXXXXXXXXX.m.cnhzalicm10pub001.ocs.aliyuncs.com").AddressList[0].ToString()); //xxxx替換為ocs控制台上的“内網位址”
            IPEndPoint ipEndPoint = new IPEndPoint(newaddress, 11211);
            // 配置檔案 - ip
            memConfig.Servers.Add(ipEndPoint);
            // 配置檔案 - 協定
            memConfig.Protocol = MemcachedProtocol.Binary;
            // 配置檔案-權限,如果使用了免密碼功能,則無需設定userName和password
            memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
            memConfig.Authentication.Parameters["zone"] = "";
            memConfig.Authentication.Parameters["userName"] = "XXXXXXXXXXXXXXXXX";
            memConfig.Authentication.Parameters["password"] = "XXXXXXXXXX";
            //下面請根據執行個體的最大連接配接數進行設定
            memConfig.SocketPool.MinPoolSize = 5;
            memConfig.SocketPool.MaxPoolSize = 200;
            MemClient = new MemcachedClient(memConfig);
        }
    }
}      
程式調用
 MemcachedHelper.SetValue(groupName,strKey, strValue, DateTime.Now.AddMinutes(5));

var restr = MemcachedHelper.GetValue(groupName,strKey);

var obj = MemcachedHelper.GetValue<Product>(groupName,"p001");      

繼續閱讀