Asp.Net Core 2.0 項目實戰(5)Memcached踩坑,基於EnyimMemcachedCore整理MemcachedHelper幫助類。

Asp.Net Core 2.0 項目實戰(1) NCMVC開源下載了html

Asp.Net Core 2.0 項目實戰(2)NCMVC一個基於Net Core2.0搭建的角色權限管理開發框架前端

Asp.Net Core 2.0 項目實戰(3)NCMVC角色權限管理前端UI預覽及下載數據庫

Asp.Net Core 2.0 項目實戰(4)ADO.NET操做數據庫封裝、 EF Core操做及實例json

Asp.Net Core 2.0 項目實戰(5)Memcached踩坑,基於EnyimMemcachedCore整理MemcachedHelper幫助類。緩存

Asp.Net Core 2.0 項目實戰(6)Redis配置、封裝幫助類RedisHelper及使用實例服務器

Asp.Net Core 2.0 項目實戰(7)MD5加密、AES&DES對稱加解密cookie

Asp.Net Core 2.0 項目實戰(8)Core下緩存操做、序列化操做、JSON操做等Helper集合類app

Asp.Net Core 2.0 項目實戰(9) 日誌記錄,基於Nlog或Microsoft.Extensions.Logging的實現及調用實例框架

Asp.Net Core 2.0 項目實戰(10) 基於cookie登陸受權認證並實現前臺會員、後臺管理員同時登陸memcached

Asp.Net Core 2.0 項目實戰(11) 基於OnActionExecuting全局過濾器,頁面操做權限過濾控制到按鈕級

Asp.Net Core2.0下使用memcached緩存。

Memcached目前微軟暫未支持,暫只支持Redis,因爲項目歷史緣由,先用博客園開源項目EnyimMemcachedCore,後續用到的時候在詳細完善測試。

MemcachedHelper此類待完善,僅供參考,註釋掉66和179行可用。net core下替代HttpContext.Current.Application.Lock()方法暫未找到。
  1 public class MemcachedHelper
  2     {
  3         private static string _DEPEND_ = "mcache_default_depend";
  4         private static string _DICT_CACHE_ = "default_core_depend_dictiaonry";
  5         private static int _EXP_ = 10 * 60; //默認緩存10分鐘 
  6         private static int HH = 3600; //1小時=3600秒
  7 
  8         static readonly object mlock = new object();
  9         private static readonly ILoggerFactory _loggerFacotry = new LoggerFactory();
 10         /// <summary>  
 11         /// 定義一個靜態MemcachedClient客戶端,它隨類一塊兒加載,全部對象共用  
 12         /// </summary>  
 13         private static MemcachedClient mclient;
 14         /// <summary>
 15         /// 構造函數,鏈接memcachedcore併爲KEYS字典開闢儲存空間
 16         /// </summary>
 17         static MemcachedHelper()
 18         {
 19             //mclient = MemCached.getInstance();
 20             if (mclient == null)
 21             {
 22                 lock (mlock)
 23                 {
 24                     if (mclient == null)
 25                     {
 26                         var options = new MemcachedClientOptions();
 27                         UtilConf.Configuration.GetSection("enyimMemcached").Bind(options);
 28                         mclient = new MemcachedClient(_loggerFacotry, new MemcachedClientConfiguration(_loggerFacotry, options));
 29                     }
 30                 }
 31             }
 32             //在緩存中開闢一個專門用來存儲Kyes的字典對象       
 33             MDictionary_SaveDict(new Dictionary<string, List<string>>());
 34         }
 35 
 36         #region ** 獲取緩存 **
 37         /// <summary>
 38         /// 獲取緩存 
 39         /// </summary>
 40         public static object Get(string key)
 41         {
 42             key = key.ToLower();
 43             return mclient.Get(key);
 44         }
 45         #endregion
 46 
 47         #region ** 添加緩存 **
 48         /// <summary> 
 49         /// 添加單個依賴項的緩存 (最小時間單位爲秒)
 50         /// </summary>         
 51         public static void Set(string depend, string key, object obj, int exp)
 52         {
 53             depend = depend.ToLower();
 54             key = key.ToLower();
 55 
 56             try
 57             {
 58                 //HttpContext.Current.Application.Lock();
 59 
 60                 //將數據加入緩存 
 61                 mclient.Add(key, obj, exp);
 62 
 63                 //HttpContext.Current.Application.UnLock();
 64 
 65                 ////將Keys加入字典 
 66                 //MDictionary_AddKeys(depend, key);
 67             }
 68             catch (System.Exception ex)
 69             {
 70                 throw new Exception(ex.Message);
 71             }
 72         }
 73 
 74         #region ++ Set的多種實現方式
 75         /// <summary>
 76         /// 默認時間
 77         /// </summary>
 78         public static void Set(string depend, string key, object obj)
 79         {
 80             MemcachedHelper.Set(depend, key, obj, _EXP_);
 81         }
 82         /// <summary>
 83         /// 默認Depend和時間
 84         /// </summary>
 85         public static void Set(string key, object obj)
 86         {
 87             MemcachedHelper.Set(_DEPEND_, key, obj, _EXP_);
 88         }
 89         /// <summary>
 90         /// 默認Depend
 91         /// </summary>
 92         public static void Set(string key, object obj, int exp)
 93         {
 94             MemcachedHelper.Set(_DEPEND_, key, obj, exp);
 95         }
 96         /// <summary>
 97         /// 長時間緩存
 98         /// </summary>
 99         public static void SetLong(string depend, string key, object obj)
100         {
101             int t = 31536000; //1年 = 10 * 365 * 24 * 60 * 60; 
102             MemcachedHelper.Set(depend, key, obj, t);
103         }
104         /// <summary>
105         /// 長時間默認depend
106         /// </summary>
107         public static void SetLong(string key, object obj)
108         {
109             int t = 31536000; //365 * 24 * 60 * 60; //1年
110             MemcachedHelper.Set(_DEPEND_, key, obj, t);
111         }
112         public static void SetAllLong(string key, object obj)
113         {
114             int t = 315360000; //365 * 24 * 60; //10年
115             MemcachedHelper.Set(_DEPEND_, key, obj, t);
116         }
117         #endregion
118 
119         #endregion
120 
121         #region ** 刪除緩存 **
122         /// <summary>
123         /// 刪除有依賴項的Keys的緩存
124         /// </summary>
125         public static void RemoveKeys(string depend, string key)
126         {
127             depend = depend.ToLower();
128             key = key.ToLower();
129 
130             try
131             {
132                 //HttpContext.Current.Application.Lock();
133 
134                 //刪除緩存                
135                 mclient.Remove(key);
136 
137                 //刪除key
138                 MDictionary_RemoveKeys(depend, key);
139 
140                 //HttpContext.Current.Application.UnLock();
141 
142             }
143             catch (System.Exception ex)
144             {
145                 throw new Exception(ex.Message);
146             }
147         }
148 
149         /// <summary>
150         /// 刪除默認depend的緩存
151         /// </summary>
152         public static void RemoveKeys(string key)
153         {
154             RemoveKeys(_DEPEND_, key);
155         }
156 
157         /// <summary>
158         /// 刪除整個依賴項
159         /// </summary>
160         public static void RemoveDepend(string depend)
161         {
162             depend = depend.ToLower();
163 
164             try
165             {
166                 //獲取keys列表
167                 List<string> keysList = MDictionary_GetKeys(depend);
168 
169                 //循環刪除數據
170                 for (int i = 0; i < keysList.Count; i++)
171                 {
172                     string k = keysList[i];
173                     //清空緩存Key
174                     mclient.Remove(k);
175                     ////清空字典下的Key 
176                     //MDictionary.RemoveKeys(depend, k);
177                 }
178                 ////清空字典 
179                 //MDictionary_RemoveDepend(depend);
180 
181             }
182             catch (System.Exception ex)
183             {
184                 throw new Exception(ex.Message);
185             }
186         }
187         #endregion
188 
189         #region --字典管理--
190 
191         #region ** 字典存取 ** 
192         /// <summary>
193         /// 取出字典
194         /// </summary>        
195         public static Dictionary<string, List<string>> MDictionary_GetDict()
196         {
197             Dictionary<string, List<string>> dict = mclient.Get(_DICT_CACHE_) as Dictionary<string, List<string>>;
198             if (dict == null)
199             {
200                 Dictionary<string, List<string>> newDict = new Dictionary<string, List<string>>();
201                 MDictionary_SaveDict(newDict);
202                 return newDict;
203             }
204             else
205             {
206                 return dict;
207             }
208         }
209 
210         /// <summary>
211         /// 存入字典
212         /// </summary>        
213         public static void MDictionary_SaveDict(Dictionary<string, List<string>> dict)
214         {
215             //默認保存360天
216             mclient.Add(_DICT_CACHE_, dict, HH * 24 * 360);
217         }
218 
219         /// <summary>
220         /// 添加並存入
221         /// </summary>
222         public static void MDictionary_AddToDictAndSave(string depend, List<string> listKeys)
223         {
224             //取出字典
225             Dictionary<string, List<string>> dict = MDictionary_GetDict();
226 
227             //修改或新增字典
228             if (dict.ContainsKey(depend))
229             {
230                 dict[depend] = listKeys; //覆蓋
231             }
232             else
233             {
234                 dict.Add(depend, listKeys); //新添加
235             }
236 
237             //存回
238             MDictionary_SaveDict(dict);
239         }
240         #endregion
241 
242         #region ** keys操做  ** 
243         /// <summary>
244         /// 根據depend獲取Keys列表
245         /// </summary>
246         public static List<string> MDictionary_GetKeys(string depend)
247         {
248             depend = depend.ToLower();
249 
250             Dictionary<string, List<string>> dict = MDictionary_GetDict();
251             if (dict.ContainsKey(depend))
252             {
253                 return dict[depend];
254             }
255             return new List<string>();
256         }
257 
258         /// <summary>
259         /// 添加keys到字典
260         /// </summary>
261         public static void MDictionary_AddKeys(string depend, string key)
262         {
263             depend = depend.ToLower();
264             key = key.ToLower();
265 
266             //添加keys列表
267             List<string> listKeys = MDictionary_GetKeys(depend);
268             if (!listKeys.Contains(key))
269             {
270                 listKeys.Add(key);
271                 //添加並存回字典
272                 MDictionary_AddToDictAndSave(depend, listKeys);
273             }
274 
275         }
276 
277         /// <summary>
278         /// 從字典中刪除一個Key
279         /// </summary>
280         public static void MDictionary_RemoveKeys(string depend, string key)
281         {
282             depend = depend.ToLower();
283             key = key.ToLower();
284 
285             List<string> listKeys = MDictionary_GetKeys(depend);
286             if (listKeys.Contains(key))
287             {
288                 listKeys.Remove(key);
289                 //添加並存回字典
290                 MDictionary_AddToDictAndSave(depend, listKeys);
291             }
292         }
293 
294         /// <summary>
295         /// 刪除depend下全部的keys列表
296         /// </summary>
297         public static void MDictionary_RemoveDepend(string depend)
298         {
299             depend = depend.ToLower();
300 
301             Dictionary<string, List<string>> dict = MDictionary_GetDict();
302             if (dict.ContainsKey(depend))
303             {
304                 dict.Remove(depend);
305                 //存回
306                 MDictionary_SaveDict(dict);
307             }
308         }
309         #endregion
310 
311         #endregion
312     }

老項目用到depend組,經過組控制組下面全部KEY/VALUE。升級Core改寫代碼過程當中瞭解到EnyimMemcachedCore相關用法,因此基於博客園Memcached整理了此類。

聽說EnyimMemcachedCore開發團隊不推薦使用靜態類,儘量地避免使用靜態類。

在使用Startup.cs中依賴注入時碰到緩存寫入失敗,暫未找到緣由,如下是個人操做步驟,有清楚的園友請留言告知,謝謝。

第一步:配置文件

 "enyimMemcached": {
    "Servers": [
      {
        "Address": "127.0.0.1",
        "Port": 11211
      }
    ]
  }

第二步:ConfigureServices配置AddEnyimMemcached

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            //memcachedcore1
            services.AddEnyimMemcached(options => Configuration.GetSection("enyimMemcached").Bind(options));
        }

第三步:Configure方法中使用

app.UseEnyimMemcached();//memcachedcore2

第四步:MVC模式下HomeController測試寫入/讀取

 private IMemcachedClient _memcachedClient;//調用memcachedcore3
 public HomeController(IMemcachedClient memcachedClient)
 {
      _memcachedClient = memcachedClient;//賦值memcachedcore4
 }
public IActionResult Index()
{

  #region --測試memcachedcore--

MemcachedHelper.Set("memcached", "memcached-core", "memcachedcore" + DateTime.Now, 60);
string mh = MemcachedHelper.Get("memcached-core").ToString();
ViewData["mhelper"] = mh;

//這種方式暫未找到合適賦值,待研究,賦值賦不上。
//刪/增/取memcachedcore5
//var cacheKey = "memcachedcore";
////_memcachedClient.Add(cacheKey, "memcachedcore" + DateTime.Now, 60);//此方法賦不上值
////var result = _memcachedClient.Get(cacheKey);
//_memcachedClient.Remove(cacheKey);
//ViewData["memcachedcore"] = result.ToString();
#endregion

}

UtilConf讀取配置文件操做類

    public class UtilConf
    {
        private static IConfiguration config;
        public static IConfiguration Configuration//加載配置文件
        {
            get
            {
                if (config != null) return config;
                config = new ConfigurationBuilder()
                    .SetBasePath(Directory.GetCurrentDirectory())
                    .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                    .Build();
                return config;
            }
            set => config = value;
        }
    }

 2017-12-08 補充

若是多臺memcached服務器,服務器時間必定要調整一致。若是不一致就會出現存不上值或過時日期不許確。

相關文章
相關標籤/搜索