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 }
时间: 2024-08-07 16:59:04

MemCaCheExtend 缓存基础操作的相关文章

Java基础课程2—— I/O 的基础操作

Java基础课程2 -- I/O 的基础操作 今天我们将了解一些面向对象编程的基本概念,什么是类.什么是函数 以及了解组成一个程序的四大功能,负责处理数据输入.输出的IO,对计算过程进行控制的逻辑控制.负责对数据进行运算的数值计算.对运行过程中产生的临时变量进行存储的缓存,以及它们是如何互相支撑.协同工作的. 什么是软件? 首先,我们学习编程,但得先弄明白什么是软件? 软件,英文名Software首先由阿兰图灵提出,在软件工程.计算机科学领域,软件即通过计算机,自动化的处理运行指令.数据的计算过

vsphere基础操作-网络

一.vsphere网络操作 概念: portgroup:通信端口组.在vsphere中,一共包含三种端口组. 1)管理网络:management network,可以理解为EXSI主机的管理IP地址.每个EXSI必须配置一个管理网络IP,使得vc能够管理到exsi.每个EXSI只能有一个唯一的管理网络. 2)内核:vmkernel,可以理解为EXSI的后端IP,使得后端各项功能能够实现.这里所说的后端功能指的是EXSI之间的通讯以实现VMOTION等高级功能.连入ISCSI或NAS等存储.FT功

Mysql安装和基础操作

1.环境检查: 先检查是否已经安装了:rpm -qa |grep mysql ---两个都检查下,查看mysql是否安装 rpm -qa |grep MySQL若安装有可删除:rpm -e ****** 2.安装:1)安装前准备:mkdir usr/mysql cd进入该目录,上传安装包到/usr/mysql目录下2)安装:rpm -ivh MySQL-server-5.0.16-0.i386.rpm rpm -ivh MySQL-elient-5.0.16-0.i386.rpm3)验证安装是否

双向链表的基础操作(C++实现)

★C++实现双向链表的基础操作(类的实现) #include<iostream> #include<cassert> using namespace std; typedef int DataType; class double_link_list {                        //定义双向链表类,包括了双向的前驱和后继指针,以及对象的初始化 public: friend class ListNode; double_link_list(DataType x =

数据结构-线性表的一些基础操作 c++代码

//线性表的顺序存储结构 template <class T> class Linearlist { public: Linearlist(int MaxListSize == 10); ~Linearlist() { delete []element; } bool IsEmpty() const { return length == 0; } bool IsFull() const { return length == MaxSize; } int Length() const { ret

php之文件基础操作

在php中对文件的基础操作非常的简单,php提供的函数粗略的用了一遍. file_get_contents():可以获取文件的内容获取一个网络资源的内容,这是php给我封装的一个比较快捷的读取文件的内容.网络资源的函数,此函数里面封装了对文件的打开,读取,关闭操作.一次性的将内容全部读取到内存中,相当方便,但是对于大文件或者网络资源较大的时候,不建议使用.file_put_contents():写入数据,和file_get_contents()类似. 文件的基础操作:touch()--新建,fo

环境变量,属性文件,文件基础操作,目录基础操作,遍历指定后缀名文件

环境变量和属性 环境变量相关: 1.得到某个/所有环境变量的值 2.设置环境变量的值 3.列出全部系统属性名 import java.util.Enumeration; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; public class Environment { public static void main(String[] args) { // TODO Auto-gener

SQLSERVER 数据库基础操作

1.修改表中字段的长度,类型为varchar,从30改到50 语句执行(注:当前为30): alter table 表名 alter column 列名 varchar(50) 2.增加字段: alter table 表名 add 字段 varchar(50) SQLSERVER 数据库基础操作,布布扣,bubuko.com

mysql的基础操作指令整理|环境redhat6

1.安装 yum-y install mysql mysql-server service mysqld start|stop|restart        ##启动|停止|重启 chkconfig mysqld on|off                  ##开机启动|关闭 此时输入:mysql就能启动进入(记得是start状态) 2.改密 mysqladmin –uroot password             ##创建密码 mysqladmin–uroot –pxxoo passw