MemCaCheExtend 缓存基础操作

  1 /// <summary>
  2 /// 在原来MemberHelper基础上修正了每次都初始化的问题,增加了对泛型的支持。改用静态构造函数来初始化 ZhangQC 2016.08.15
  3 /// </summary>
  4 public class MemcacheExtend
  5 {
  6 //日志
  7 public static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
  8 
  9 /// <summary>
 10 /// 初始化
 11 /// </summary>
 12 static MemcacheExtend()
 13 {
 14 Initialize();
 15 }
 16 
 17 private static readonly string Nserver = ConfigurationManager.AppSettings["Nserver"];
 18 
 19 /// <summary> 
 20 /// 初始化池
 21 /// </summary>
 22 public static void Initialize()
 23 {
 24 try
 25 {
 26 //分布Memcachedf服务IP 端口 
 27 string[] servers = { Nserver };
 28 
 29 SockIOPool pool = SockIOPool.GetInstance();
 30 
 31 pool.SetServers(servers);
 32 pool.InitConnections = 3;
 33 pool.MinConnections = 3;
 34 pool.MaxConnections = 5;
 35 pool.SocketConnectTimeout = 1000000;
 36 pool.SocketTimeout = 3000000;
 37 pool.MaintenanceSleep = 30;
 38 pool.Failover = true;
 39 pool.Nagle = false;
 40 pool.Initialize();
 41 }
 42 catch (Exception ex)
 43 {
 44 Log.ErrorFormat("初始化Memcached失败:{0}", ex);
 45 }
 46 }
 47 
 48 /// <summary>
 49 /// 插入缓存
 50 /// </summary>
 51 /// <param name="key">关键字</param>
 52 /// <param name="value">内容</param>
 53 /// <returns>返回是否插入成功(true 成功 | false 失败)</returns>
 54 public static bool InsertMemcached(string key, object value)
 55 {
 56 bool result = false;
 57 try
 58 {
 59 //缓存
 60 MemcachedClient mc = new MemcachedClient();
 61 mc.EnableCompression = false;
 62 if (!mc.KeyExists(key))
 63 {
 64 //key值不存在时,添加缓存记录
 65 result = mc.Add(key, value,
 66 DateTime.Now.AddDays(Convert.ToInt32(ConfigurationManager.AppSettings["CacheExpiry"])));
 67 }
 68 }
 69 catch (Exception ex)
 70 {
 71 Log.ErrorFormat("插入缓存时出错:{0}", ex);
 72 }
 73 return result;
 74 }
 75 
 76 /// <summary>
 77 /// 删除缓存中的记录
 78 /// </summary>
 79 /// <param name="key"></param>
 80 /// <returns></returns>
 81 public static bool DeleteMemcached(string key)
 82 {
 83 bool result = false;
 84 try
 85 {
 86 //缓存
 87 MemcachedClient mc = new MemcachedClient();
 88 mc.EnableCompression = false;
 89 if (mc.KeyExists(key))
 90 {
 91 //存在key值,删除与此key值的信息
 92 result = mc.Delete(key);
 93 }
 94 }
 95 catch (Exception ex)
 96 {
 97 Log.ErrorFormat("删除缓存记录时失败:{0}", ex);
 98 }
 99 return result;
100 }
101 
102 /// <summary>
103 /// 清空缓存
104 /// </summary>
105 public static void FlushMemcached()
106 {
107 try
108 {
109 MemcachedClient mc = new MemcachedClient();
110 mc.EnableCompression = false;
111 mc.FlushAll();
112 }
113 catch (Exception ex)
114 {
115 Log.ErrorFormat("情况缓存时出错:{0}", ex);
116 }
117 }
118 /// <summary>
119 /// 获取某个键值下的value
120 /// </summary>
121 /// <param name="key"></param>
122 /// <returns></returns>
123 public static object GetMemcached(string key)
124 {
125 object value = null;
126 MemcachedClient mc = new MemcachedClient();
127 mc.EnableCompression = false;
128 
129 if (mc.KeyExists(key))
130 {
131 //存在key值,获取与此key值对应的value
132 value = mc.Get(key);
133 }
134 return value;
135 }
136 
137 /// <summary>
138 /// 根据键值获取对应的缓存数据
139 /// </summary>
140 /// <typeparam name="T"></typeparam>
141 /// <param name="key"></param>
142 /// <returns></returns>
143 public static T GetMemcached<T>(string key)
144 {
145 
146 T value = default(T);
147 try
148 {
149 MemcachedClient mc = new MemcachedClient();
150 mc.EnableCompression = false;
151 
152 if (mc.KeyExists(key))
153 {
154 //存在key值,获取与此key值对应的value
155 value = (T)mc.Get(key);
156 }
157 else
158 {
159 value = default(T);
160 }
161 }
162 catch (Exception ex)
163 {
164 Log.ErrorFormat("根据键值获取对应的缓存数据时出错:{0}", ex);
165 }
166 return value;
167 }
168 
169 
170 /// <summary>
171 /// 获取多个键值下的value
172 /// </summary>
173 /// <param name="keys">多个Key值</param>
174 /// <returns></returns>
175 public static object[] GetMultipleMemcached(string[] keys)
176 {
177 object[] value = null;
178 MemcachedClient mc = new MemcachedClient();
179 mc.EnableCompression = false;
180 //获取多个键值下的
181 value = mc.GetMultipleArray(keys);
182 return value;
183 }
184 
185 /// <summary>
186 /// 判断键值是否存在
187 /// </summary>
188 /// <param name="key"></param>
189 /// <returns></returns>
190 public static bool KeyExists(string key)
191 {
192 bool result = false;
193 MemcachedClient mc = new MemcachedClient();
194 mc.EnableCompression = false;
195 if (mc.KeyExists(key))
196 {
197 result = true;
198 }
199 else
200 {
201 result = false;
202 }
203 return result;
204 }
205 
206 /// <summary>
207 /// 替换缓存的数据
208 /// </summary>
209 /// <param name="key"></param>
210 /// <param name="value"></param>
211 /// <returns></returns>
212 public static bool Replace(string key, object value)
213 {
214 bool result = false;
215 //缓存
216 MemcachedClient mc = new MemcachedClient();
217 mc.EnableCompression = false;
218 if (mc.KeyExists(key))
219 {
220 //存在Key值,进行替换
221 result = mc.Replace(key, value);
222 }
223 else
224 {
225 //如果不存在进行插入
226 result=InsertMemcached(key, value);
227 }
228 return result;
229 }
230 
231 /// <summary>
232 /// 根据键获取值
233 /// </summary>
234 /// <param name="elementsValue"></param>
235 /// <param name="key"></param>
236 /// <returns></returns>
237 public static object GetValue(Dictionary<string, object> elementsValue, string key)
238 {
239 //缓存值不为空
240 // ReSharper disable once LoopCanBeConvertedToQuery
241 foreach (var item in elementsValue)
242 {
243 //存在键值对,返回object
244 if (item.Key == key)
245 {
246 return item.Value;
247 }
248 }
249 return null;
250 }
251 
252 
253 /// <summary>
254 /// 将获取到的值添加到缓存中
255 /// </summary>
256 /// <param name="key">键值对Key</param>
257 /// <param name="value">键值对Value</param>
258 /// <param name="parentKey">缓存Key</param>
259 public static void AddValue(string key, object value, string parentKey)
260 {
261 
262 //实例化键值对
263 var elements = new Dictionary<string, object> { { key, value } };
264 //将key和Value组合成键值对
265 //将键值对追加缓存中
266 InsertMemcached(parentKey, elements);
267 }
268 
269 
270 /// <summary>
271 /// 尝试获取缓存,如果获取不到,执行匿名委托操作
272 /// </summary>
273 /// <typeparam name="T"></typeparam>
274 /// <param name="cacheKey"></param>
275 /// <param name="func"></param>
276 /// <returns></returns>
277 public static T TryGetFromCache<T>(string cacheKey, Func<T> func) where T : class
278 {
279 T value = default(T);
280 try
281 {
282 value = GetMemcached<T>(cacheKey);
283 //value还是默认值,那么代表没有获取到缓存
284 if (value == null || value.Equals(default(T)))
285 {
286 value = func.Invoke();
287 Replace(cacheKey, value);
288 }
289 }
290 catch (Exception ex)
291 {
292 Log.ErrorFormat("尝试获取缓存出错:{0}", ex);
293 }
294 finally
295 {
296 
297 }
298 return value;
299 }
300 
301 
302 /// <summary>
303 /// 尝试获取缓存,如果获取不到,执行匿名委托操作
304 /// </summary>
305 /// <typeparam name="T"></typeparam>
306 /// <param name="cacheKey"></param>
307 /// <param name="func"></param>
308 /// <returns></returns>
309 public static List<T> TryGetFromCache<T>(string cacheKey, Func<List<T>> func) where T : class
310 {
311 var value = default(List<T>);
312 try
313 {
314 value = GetMemcached<List<T>>(cacheKey);
315 //value还是默认值,那么代表没有获取到缓存
316 if (value == null || value.Equals(default(T)))
317 {
318 value = func.Invoke();
319 Replace(cacheKey, value);
320 }
321 }
322 catch (Exception ex)
323 {
324 Log.ErrorFormat("尝试获取缓存出错:{0}", ex);
325 }
326 return value;
327 }
328 }

 

posted @ 2017-01-20 10:28  小小的菜鸟程序员  阅读(162)  评论(0编辑  收藏  举报