阿里雲的開放式分布式緩存(OCS)簡化了緩存的運維管理,使用起來很方便,官方推薦的.NET訪問客戶端類庫為 Enyim.Caching,下面對此做一個封裝。
首先引用最新版本 Enyim.Caching ,比如2.13.2.0 版本。
先按照阿里雲的示例代碼,封裝一個基礎的 MemCached訪問類:
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() { //初始化緩存 string host = System.Configuration.ConfigurationManager.AppSettings["MemoryCacheServer"]; MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration(); IPAddress newaddress = IPAddress.Parse(Dns.GetHostEntry (host).AddressList[0].ToString());//your_ocs_host替換為OCS內網地址 IPEndPoint ipEndPoint = new IPEndPoint(newaddress, 11211); // 配置文件 - ip memConfig.Servers.Add(ipEndPoint); // 配置文件 - 協議 memConfig.Protocol = MemcachedProtocol.Binary; // 配置文件-權限 memConfig.Authentication.Type = typeof(PlainTextAuthenticator); memConfig.Authentication.Parameters["zone"] = ""; memConfig.Authentication.Parameters["userName"] = System.Configuration.ConfigurationManager.AppSettings["CacheServerUID"]; memConfig.Authentication.Parameters["password"] = System.Configuration.ConfigurationManager.AppSettings["CacheServerPWD"]; //下面請根據實例的最大連接數進行設置 memConfig.SocketPool.MinPoolSize = 5; memConfig.SocketPool.MaxPoolSize = 200; MemClient=new MemcachedClient(memConfig); //如果采用配置文件,可以注釋上面代碼,直接下面一行代碼: //MemClient = new MemcachedClient(); } }
再定義一個緩存訪問接口:
public interface ICacheManager { /// <summary> /// 是否啟用緩存 /// </summary> bool IsEnabled { get; } /// <summary> /// 根據key取緩存對象 /// </summary> T Get<T>(string key); object Get(string key); /// <summary> /// 放入緩存 /// </summary> bool Set(string key, object data, int cacheTime); /// <summary> /// 是否在緩存中 /// </summary> bool IsSet(string key); /// <summary> /// 從緩存刪除 /// </summary> void Remove(string key); /// <summary> /// 根據規則刪除 /// </summary> void RemoveByPattern(string pattern); /// <summary> /// 清空所有緩存 /// </summary> void Clear(); }
最后封裝 OCSManager:
public class OCSManager : ICacheManager { private static readonly MemcachedClient cache; private static readonly OCSManager instance; private OCSManager() { } static OCSManager() { cache = MemCached.getInstance(); instance = new OCSManager(); } private static bool isServerConnected = true; public static ICacheManager Instance { get { return instance; } } #region ICacheManager 成員 public bool IsEnabled { get { return cache != null && isServerConnected; } } public T Get<T>(string key) { //var result = cache.ExecuteGet<T>(key); //return result.Value; return cache.Get<T>(key); } public object Get(string key) { return cache.Get(key); } public bool Set(string key, object data, int cacheTime) { if (data == null) return false; //var result= cache.ExecuteStore (Enyim.Caching.Memcached.StoreMode.Add,key,data,DateTime.Now + TimeSpan.FromMinutes(cacheTime)); //return result.Success; return cache.Store(Enyim.Caching.Memcached.StoreMode.Set, key, data, DateTime.Now + TimeSpan.FromMinutes(cacheTime)); } public bool IsSet(string key) { object obj; return cache.TryGet(key, out obj); } public void Remove(string key) { cache.Remove(key); } public void RemoveByPattern(string pattern) { //throw new NotImplementedException(); } public void Clear() { cache.FlushAll(); } #endregion }
最后,在應用程序配置文件,增加上如下的配置節點:
<configSections> <sectionGroup name="enyim.com"> <section name="memcached" type="Enyim.Caching.Configuration.MemcachedClientSection, Enyim.Caching" /> </sectionGroup> </configSections> <enyim.com> <memcached protocol="Binary"> <servers> <add address="192.168.70.1" port="11211" /> </servers> <socketPool minPoolSize="20" maxPoolSize="500" connectionTimeout="00:00:01" deadTimeout="00:00:01" receiveTimeout="00:00:01" /> <authentication type="Enyim.Caching.Memcached.PlainTextAuthenticator,Enyim.Caching" zone="" userName="" password="" /> </memcached> </enyim.com>
注意:OCS使用的時候,會分配指定的用戶名和密碼, userName="" password="" ,請在實際使用之前做好這個配置。