世界足球俱乐部排名,小仓优子 bt,河南省体育中心游泳馆
下面来正式分享今天的文章吧:
。搭建redis服务端,并用客户端连接
。封装缓存父类,定义get,set等常用方法
。定义rediscache缓存类,执行redis的get,set方法
。构造出缓存工厂调用方法
下面一步一个脚印的来分享:
。搭建redis服务端,并用客户端连接
首先,咋们去这个地址下载安装文件,我这里的版本是:redis-2.4.5-win32-win64里面有32位和64位的执行文件,我这里服务器是64位的下面给出截图和用到部分程序的说明:
现在,咋们直接可以用鼠标双击redis-server.exe这个应用程序,这样就打开了redis服务窗体(您也可以下载一个windows服务承载器,把redis服务运行在windows的服务中,就不用担心每次关闭redis服务黑色窗体后无法访问redis了),运行起来是这样:
有红色框的信息就表示成功了,这里redis服务监听的端口默认是6379,要修改端口或者更多的配置信息请找到redis.conf配置文件,具体配置信息介绍可以来这里
再来,打开客户端连接服务端,咋们退到64bit文件夹的目录中,鼠标移到64bit文件夹上并且安装shift键,同时点击鼠标的右键,选中"在此处打开命令窗口"这样快速进入到了该文件夹的cmd命令窗口中(当然不同的操作系统不同,这里演示的是windows的操作;还有其他进入的方式这里不做介绍,因为个人感觉这是最快的);然后,在命令窗口中录入redis-cli.exe -h localhost -p 6379回车来访问服务端,效果图:
再来看下服务端窗体截图:
没错这样客户端就连接上服务端了,可以简单在客户端执行下set,get命令:
如果是客户端要访问远程的redis服务端,只需要把localhost换成可访问的ip就行了如果还需要密码等更多配置请去上面的那个地址链接;
。封装缓存父类,定义get,set等常用方法
先来,上父类的代码:
public class basecache : idisposable { protected string def_ip = string.empty; protected int def_port = 0; protected string def_password = string.empty; public basecache() { } public virtual void initcache(string ip = "", int port = 0, string password = "") { } public virtual bool setcache<t>(string key, t t, int timeoutminute = 10) where t : class,new() { return false; } public virtual t getcache<t>(string key) where t : class,new() { return default(t); } public virtual bool remove(string key) { return false; } public virtual bool flushall() { return false; } public virtual bool any(string key) { return false; } public virtual void dispose(bool isfalse) { if (isfalse) { } } //手动释放 public void dispose() { this.dispose(true); //不自动释放 gc.suppressfinalize(this); } }
这里定义的方法没有太多的注释,更多的意思我想看方法名称就明白了,这个父类主要实现了idisposable,实现的dispose()中主要用来释放资源并且自定义了一个 public virtual void dispose(bool isfalse)方法,这里面有一句是gc.suppressfinalize(this);按照官网介绍的意思是阻塞自动释放资源,其他的没有什么了,继续看下面的
。定义rediscache缓存类,执行redis的get,set方法
首先,咋们分别定义类rediscache,memcachedcache(这里暂未实现对memcache缓存的操作),并且继承basecache,重写set,get方法如下代码:
/// <summary> /// redis缓存 /// </summary> public class rediscache : basecache { public redisclient redis = null; public rediscache() { //这里去读取默认配置文件数据 def_ip = "172.0.0.1"; def_port = 6379; def_password = ""; } #region redis缓存 public override void initcache(string ip = "", int port = 0, string password = "") { if (redis == null) { ip = string.isnullorempty(ip) ? def_ip : ip; port = port == 0 ? def_port : port; password = string.isnullorempty(password) ? def_password : password; redis = new redisclient(ip, port, password); } } public override bool setcache<t>(string key, t t, int timeoutminute = 10) { var isfalse = false; try { if (string.isnullorempty(key)) { return isfalse; } initcache(); isfalse = redis.set<t>(key, t, timespan.fromminutes(timeoutminute)); } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override t getcache<t>(string key) { var t = default(t); try { if (string.isnullorempty(key)) { return t; } initcache(); t = redis.get<t>(key); } catch (exception ex) { } finally { this.dispose(); } return t; } public override bool remove(string key) { var isfalse = false; try { if (string.isnullorempty(key)) { return isfalse; } initcache(); isfalse = redis.remove(key); } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override void dispose(bool isfalse) { if (isfalse && redis != null) { redis.dispose(); redis = null; } } #endregion } /// <summary> /// memcached缓存 /// </summary> public class memcachedcache : basecache { }
这里,用到的redisclient类是来自nuget包引用的,这里nuget包是:
然后,来看下重写的initcache方法,这里面有一些ip,port(端口),password(密码)参数,这里直接写入在cs文件中没有从配置文件读取,大家可以扩展下;这些参数通过redisclient构造函数传递给底层socket访问需要的信息,下面简单展示下redisclient几个的构造函数:
public redisclient(); public redisclient(redisendpoint config); public redisclient(string host); public redisclient(uri uri); public redisclient(string host, int port); public redisclient(string host, int port, string password = null, long db = 0);
至于get,set方法最终都是使用redisclient对象访问的,个人觉得需要注意的是set方法里面的过期时间参数,目前还没有试验这种情况的效果:
?通过这几种方法设置过期时间后,快到过期时间的时候如果此时有使用这个缓存key那么过期时间是否会往后自动增加过期时间有效期,这里暂时没有试验(这里是由于前面项目中的.net core框架中的memecache缓存都有这种设置,想来redis应该也有吧)
这里,需要重写下public override void dispose(bool isfalse)方法,因为调用完redisclient后需要释放,我们通过dispose统一来手动释放,而不是直接在调用的时候使用using()
。构造出缓存工厂调用方法
接下来,咋们需要定义一个缓存工厂,因为上面刚才定义了一个rediscache和memcachedcache明显这里会有多个不同缓存的方法调用,所用咋们来定义个工厂模式来调用对应的缓存;这里的工厂模式没有使用直接显示创建new rediscache(),new memcachedcache()对象的方法,而是使用了反射的原理,创建对应的缓存对象;
先来,定义个枚举,枚举里面的声明的名字要和咋们缓存类的名称相同,代码如下:
public enum cachetype { rediscache, memcachedcache }
再来,定义个工厂来cacherepository(缓存工厂),并且定义方法current如下代码:
public static basecache current(cachetype cachetype = cachetype.rediscache) { var nspace = typeof(basecache); var fullname = nspace.fullname; var nowspace = fullname.substring(0, fullname.lastindexof('.') + 1); return assembly.getexecutingassembly().createinstance(nowspace + cachetype.tostring(), true) as basecache; }
*:通过传递枚举参数,来确定反射createinstance()方法需要用到的typename参数,从而来定义需要访问的那个缓存对象,这里要注意的是加上了一个命名空间nowspace,因为缓存类可能和工厂类不是同一个命名空间,但是通常会和缓存基类是同命名空间所以在方法最开始的时候截取获取了缓存类需要的命名空间(这里看自身项目来定吧);
*:assembly.getexecutingassembly()这个是用来获取当前应用程序集的路径,这里就避免了咋们使用assembly.load()方法还需要传递程序集的路径地址了
好了满上上面要求后,咋们可以在测试页面调用代码如:cacherepository.current(cachetype.rediscache).setcache<moflightsearchresponse>(keydata, value);就如此简单,咋们使用redis-cli.exe客户端来看下缓存起来的数据:
怎么样,您们的是什么效果呢,下面给出整体代码
#region cacherepository 缓存工厂(默认存储session中) /// <summary> /// 缓存枚举 /// </summary> public enum cachetype { basecache, rediscache, memcachedcache } /// <summary> /// 缓存工厂(默认存储session中) /// </summary> public class cacherepository { /// <summary> /// 缓存工厂(默认存储session中, cachekey = "seesionkey") /// </summary> /// <param name="cachetype">缓存类型</param> /// <returns></returns> public static basecache current(cachetype cachetype = cachetype.rediscache) { var nspace = typeof(basecache); var fullname = nspace.fullname; var nowspace = fullname.substring(0, fullname.lastindexof('.') + 1); return assembly.getexecutingassembly().createinstance(nowspace + cachetype.tostring(), true) as basecache; } } /// <summary> /// 缓存基类(默认存储session中) /// </summary> public class basecache : idisposable { protected string def_ip = string.empty; protected int def_port = 0; protected string def_password = string.empty; protected string cachekey = "seesionkey"; public basecache() { } /// <summary> /// 获取自定义sessionid值 /// </summary> /// <param name="key">key:使用唯一的登陆账号</param> /// <returns>hash值的sessionid</returns> public virtual string getsessionid(string key) { return md5extend.getsidmd5hash(key); } public virtual void initcache(bool isreadandwriter = true, string ip = "", int port = 0, string password = "") { } public virtual bool setcache<t>(string key, t t, int timeoutminute = 10, bool isserilize = false) where t : class,new() { var isfalse = false; try { key = key ?? cachekey; if (t == null) { return isfalse; } var session_json = jsonconvert.serializeobject(t); httpcontext.current.session.timeout = timeoutminute; httpcontext.current.session.add(key, session_json); isfalse = true; } catch (exception ex) { throw new exception(ex.message); } return isfalse; } public virtual t getcache<t>(string key = null, bool isserilize = false) where t : class,new() { var t = default(t); try { key = key ?? cachekey; var session = httpcontext.current.session[key]; if (session == null) { return t; } t = jsonconvert.deserializeobject<t>(session.tostring()); } catch (exception ex) { throw new exception(ex.message); } return t; } public virtual bool remove(string key = null) { var isfalse = false; try { key = key ?? cachekey; httpcontext.current.session.remove(key); isfalse = true; } catch (exception ex) { throw new exception(ex.message); } return isfalse; } /// <summary> /// 增加缓存时间 /// </summary> /// <returns></returns> public virtual bool addexpire(string key, int ntimeminute = 10) { return true; } public virtual bool flushall() { return false; } public virtual bool any(string key) { return false; } public virtual bool sethashcache<t>(string hashid, string key, t t, int ntimeminute = 10) where t : class,new() { return false; } public virtual list<string> gethashkeys(string hashid) { return null; } public virtual list<string> gethashvalues(string hashid) { return null; } public virtual t gethashvalue<t>(string hashid, string key) where t : class,new() { var t = default(t); return t; } public virtual bool removehashbykey(string hashid, string key) { return false; } public virtual void dispose(bool isfalse) { if (isfalse) { } } //手动释放 public void dispose() { this.dispose(true); //不自动释放 gc.suppressfinalize(this); } } /// <summary> /// redis缓存 /// </summary> public class rediscache : basecache { public iredisclient redis = null; public rediscache() { //这里去读取默认配置文件数据 def_ip = "127.0.0.1"; def_port = 6379; def_password = ""; } #region redis缓存 public static object _lockcache = new object(); public override void initcache(bool isreadandwriter = true, string ip = "", int port = 0, string password = "") { if (redis == null) { ip = string.isnullorempty(ip) ? def_ip : ip; port = port == 0 ? def_port : port; password = string.isnullorempty(password) ? def_password : password; //单个redis服务 //redis = new redisclient(ip, port, password); //集群服务 如果密码,格式如:pwd@ip:port var readandwriteports = new list<string> { "shenniubuxing3@127.0.0.1:6379" }; var onlyreadports = new list<string> { "shenniubuxing3@127.0.0.1:6378", "shenniubuxing3@127.0.0.1:6377" }; var redispool = new pooledredisclientmanager( readandwriteports, onlyreadports, new redisclientmanagerconfig { autostart = true, //最大读取链接 maxreadpoolsize = 20, //最大写入链接 maxwritepoolsize = 10 }) { //每个链接超时时间 connecttimeout = 20, //连接池超时时间 pooltimeout = 60 }; lock (_lockcache) { redis = isreadandwriter ? redispool.getclient() : redispool.getreadonlyclient(); } } } public override bool addexpire(string key, int ntimeminute = 10) { var isfalse = false; try { if (string.isnullorempty(key)) { return isfalse; } initcache(); //isfalse = redis.expireentryin(key, timespan.fromminutes(ntimeminute)); isfalse = redis.expireentryat(key, datetime.now.addminutes(ntimeminute)); } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override bool setcache<t>(string key, t t, int timeoutminute = 10, bool isserilize = false) { var isfalse = false; try { if (string.isnullorempty(key)) { return isfalse; } initcache(); if (isserilize) { var data = jsonconvert.serializeobject(t); var bb = system.text.encoding.utf8.getbytes(data); isfalse = redis.set<byte[]>(key, bb, timespan.fromminutes(timeoutminute)); } else { isfalse = redis.set<t>(key, t, timespan.fromminutes(timeoutminute)); } } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override t getcache<t>(string key, bool isserilize = false) { var t = default(t); try { if (string.isnullorempty(key)) { return t; } initcache(false); if (isserilize) { var bb = redis.get<byte[]>(key); if (bb.length <= 0) { return t; } var data = system.text.encoding.utf8.getstring(bb); t = jsonconvert.deserializeobject<t>(data); } else { t = redis.get<t>(key); } } catch (exception ex) { } finally { this.dispose(); } return t; } public override bool remove(string key) { var isfalse = false; try { if (string.isnullorempty(key)) { return isfalse; } initcache(); isfalse = redis.remove(key); } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override bool sethashcache<t>(string hashid, string key, t t, int ntimeminute = 10) { var isfalse = false; try { if (string.isnullorempty(hashid) || string.isnullorempty(key) || t == null) { return isfalse; } initcache(); var result = jsonconvert.serializeobject(t); if (string.isnullorempty(result)) { return isfalse; } isfalse = redis.setentryinhash(hashid, key, result); if (isfalse) { addexpire(key, ntimeminute); } } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override list<string> gethashkeys(string hashid) { var hashkeys = new list<string>(); try { if (string.isnullorempty(hashid)) { return hashkeys; } initcache(); hashkeys = redis.gethashkeys(hashid); } catch (exception ex) { } finally { this.dispose(); } return hashkeys; } public override list<string> gethashvalues(string hashid) { var hashvalues = new list<string>(); try { if (string.isnullorempty(hashid)) { return hashvalues; } initcache(); hashvalues = redis.gethashvalues(hashid); } catch (exception ex) { } finally { this.dispose(); } return hashvalues; } public override t gethashvalue<t>(string hashid, string key) { var t = default(t); try { if (string.isnullorempty(hashid) || string.isnullorempty(key)) { return t; } initcache(); var result = redis.getvaluefromhash(hashid, key); if (string.isnullorempty(result)) { return t; } t = jsonconvert.deserializeobject<t>(result); } catch (exception ex) { } finally { this.dispose(); } return t; } public override bool removehashbykey(string hashid, string key) { var isfalse = false; try { if (string.isnullorempty(hashid) || string.isnullorempty(key)) { return isfalse; } initcache(); isfalse = redis.removeentryfromhash(hashid, key); } catch (exception ex) { } finally { this.dispose(); } return isfalse; } public override void dispose(bool isfalse) { if (isfalse && redis != null) { redis.dispose(); redis = null; } } #endregion } /// <summary> /// memcached缓存 /// </summary> public class memcachedcache : basecache { } #endregion
这次分享的redis缓存从搭建到使用希望给您们有帮助,还请多多支持点赞,谢谢。
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持移动技术网!
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
Net Core Web Api项目与在NginX下发布的方法
asp.net core3.1 引用的元包dll版本兼容性问题解决方案
IdentityServer4实现.Net Core API接口权限认证(快速入门)
ASP.NET Core MVC通过IViewLocationExpander扩展视图搜索路径的实现
网友评论