C# 通过ServiceStack 操作Redis——String类型的使用及示例
1.引用Nuget包 ServiceStack.Redis
我这里就用别人已经封装好的Reids操作类来和大家一起参考了下,看看怎么使用ServiceStack.Redis 操作Redis数据
RedisConfigInfo--redis配置文件信息
/// <summary> /// redis配置文件信息 /// 也可以放到配置文件去 /// </summary> public sealed class RedisConfigInfo { /// <summary> /// 可写的Redis链接地址 /// format:ip1,ip2 /// /// 默认6379端口 /// </summary> public string WriteServerList = "127.0.0.1:6379"; /// <summary> /// 可读的Redis链接地址 /// format:ip1,ip2 /// </summary> public string ReadServerList = "127.0.0.1:6379"; /// <summary> /// 最大写链接数 /// </summary> public int MaxWritePoolSize = 60; /// <summary> /// 最大读链接数 /// </summary> public int MaxReadPoolSize = 60; /// <summary> /// 本地缓存到期时间,单位:秒 /// </summary> public int LocalCacheTime = 180; /// <summary> /// 自动重启 /// </summary> public bool AutoStart = true; /// <summary> /// 是否记录日志,该设置仅用于排查redis运行时出现的问题, /// 如redis工作正常,请关闭该项 /// </summary> public bool RecordeLog = false; }
RedisManager --Redis管理中心 创建Redis链接
/// <summary> /// Redis管理中心 创建Redis链接 /// </summary> public class RedisManager { /// <summary> /// redis配置文件信息 /// </summary> private static RedisConfigInfo RedisConfigInfo = new RedisConfigInfo(); /// <summary> /// Redis客户端池化管理 /// </summary> private static PooledRedisClientManager prcManager; /// <summary> /// 静态构造方法,初始化链接池管理对象 /// </summary> static RedisManager() { CreateManager(); } /// <summary> /// 创建链接池管理对象 /// </summary> private static void CreateManager() { string[] WriteServerConStr = RedisConfigInfo.WriteServerList.Split(','); string[] ReadServerConStr = RedisConfigInfo.ReadServerList.Split(','); prcManager = new PooledRedisClientManager(ReadServerConStr, WriteServerConStr, new RedisClientManagerConfig { MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize, MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize, AutoStart = RedisConfigInfo.AutoStart, }); } /// <summary> /// 客户端缓存操作对象 /// </summary> public static IRedisClient GetClient() { return prcManager.GetClient(); } }
RedisBase-- 是redis操作的基类,继承自IDisposable接口,主要用于释放内存
/// <summary> /// RedisBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存 /// </summary> public abstract class RedisBase : IDisposable { public IRedisClient iClient { get; private set; } /// <summary> /// 构造时完成链接的打开 /// </summary> public RedisBase() { iClient = RedisManager.GetClient(); } //public static IRedisClient iClient { get; private set; } //static RedisBase() //{ // iClient = RedisManager.GetClient(); //} private bool _disposed = false; protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { iClient.Dispose(); iClient = null; } } this._disposed = true; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } public void Transcation() { using (IRedisTransaction irt = this.iClient.CreateTransaction()) { try { irt.QueueCommand(r => r.Set("key", 20)); irt.QueueCommand(r => r.Increment("key", 1)); irt.Commit(); // 提交事务 } catch (Exception ex) { irt.Rollback(); throw ex; } } } /// <summary> /// 清除全部数据 请小心 /// </summary> public virtual void FlushAll() { iClient.FlushAll(); } /// <summary> /// 保存数据DB文件到硬盘 /// </summary> public void Save() { iClient.Save();//阻塞式save } /// <summary> /// 异步保存数据DB文件到硬盘 /// </summary> public void SaveAsync() { iClient.SaveAsync();//异步save } }
RedisStringService--String类型操作帮助类
/// <summary> /// key-value 键值对:value可以是序列化的数据 /// </summary> public class RedisStringService : RedisBase { #region 赋值 /// <summary> /// 设置key的value /// </summary> public bool Set<T>(string key, T value) { //iClient.Db =2; return base.iClient.Set<T>(key, value); } /// <summary> /// 设置key的value并设置过期时间 /// </summary> public bool Set<T>(string key, T value, DateTime dt) { //iClient.Db = 2; return base.iClient.Set<T>(key, value, dt); } /// <summary> /// 设置key的value并设置过期时间 /// </summary> public bool Set<T>(string key, T value, TimeSpan sp) { //iClient.Db = 2; return base.iClient.Set<T>(key, value, sp); } /// <summary> /// 设置多个key/value 可以一次保存多个key value ---多个key value 不是分多次,是一个独立的命令; /// </summary> public void Set(Dictionary<string, string> dic) { //iClient.Db = 2; base.iClient.SetAll(dic); } #endregion #region 追加 /// <summary> /// 在原有key的value值之后追加value,没有就新增一项 /// </summary> public long Append(string key, string value) { return base.iClient.AppendToValue(key, value); } #endregion #region 获取值 /// <summary> /// 获取key的value值 /// </summary> public string Get(string key) { return base.iClient.GetValue(key); } /// <summary> /// 获取多个key的value值 /// </summary> public List<string> Get(List<string> keys) { return base.iClient.GetValues(keys); } /// <summary> /// 获取多个key的value值 /// </summary> public List<T> Get<T>(List<string> keys) { return base.iClient.GetValues<T>(keys); } #endregion #region 获取旧值赋上新值 /// <summary> /// 获取旧值赋上新值 /// </summary> public string GetAndSetValue(string key, string value) { return base.iClient.GetAndSetValue(key, value); } #endregion #region 辅助方法 /// <summary> /// 获取值的长度 /// </summary> public long GetLength(string key) { return base.iClient.GetStringCount(key); } /// <summary> /// 自增1,返回自增后的值 保存的是10 调用后,+1 返回11 /// </summary> public long Incr(string key) { return base.iClient.IncrementValue(key); } /// <summary> /// 自增count,返回自增后的值 自定义自增的步长值 /// </summary> public long IncrBy(string key, int count) { return base.iClient.IncrementValueBy(key, count); } /// <summary> /// 自减1,返回自减后的值,Redis操作是单线程操作;不会出现超卖的情况 /// </summary> public long Decr(string key) { return base.iClient.DecrementValue(key); } /// <summary> /// 自减count ,返回自减后的值 /// </summary> /// <param name="key"></param> /// <param name="count"></param> /// <returns></returns> public long DecrBy(string key, int count) { return base.iClient.DecrementValueBy(key, count); } #endregion }
nuget包是外国人写的,在国内并没有完整的中文文档,也没有专门的人来翻译、封装它,所以上面的代码方法不是很全,还有很多api方法需要自己去官网找然后自己封装。
在这里,上面的封装我就放一边,还是给大家演示ServiceStack原生的API如何使用
2. string 类型的使用
public static RedisClient client = new RedisClient("127.0.0.1", 6379);
//1.存入键值对 bool a = client.Set("key_name", "value_11"); //2. 根据key获取值 string data1= client.GetValue("key_name"); //3. 在原有的value上进行追加 long data2 = client.AppendToValue("key_name", "value_11"); // 4.获取值的长度 var data3=client.GetStringCount("key_name"); //5. 数值自增/减,返回自增、自减后的值 client.Set("小明分数", 100); //自增20,可以自增负值 var data4= client.IncrementValueBy("小明分数", 20); //自减50 var data5 = client.DecrementValueBy("小明分数", 50); //6. 插入实体和读取实体 UserInfo userInfo = new UserInfo() { Id = 3, Age = 50, Name = "zxl", Pwd = "123456" }; client.Set("UserInfo_Id_3", userInfo); UserInfo data6 = client.Get<UserInfo>("UserInfo_Id_3"); //7. 一次性添加多个key-value集合 Dictionary<string, string> dic = new Dictionary<string, string>() { { "101", Guid.NewGuid().ToString("N")}, { "102", Guid.NewGuid().ToString("N")}, { "103", Guid.NewGuid().ToString("N")}, { "104", Guid.NewGuid().ToString("N")}, { "105", Guid.NewGuid().ToString("N")}, { "106", Guid.NewGuid().ToString("N")} }; client.SetAll(dic); //8.获取多个key的 value值集合 List<string> keys = new List<string>(){ "101", "103", "105" }; List<string> data8= client.GetValues(keys);
//9. 重命名key client.Rename("106", "1066"); //10. 设置key的过期时间(30秒后自动销毁) bool b2= client.Expire("102", 30); //11. 删除单个key bool d1 = client.Remove("101");//删除成功,返回true bool d2 = client.Remove("ffff"); //删除不存在的数据,返回false
//12. 删除多个key IEnumerable<string> delete_keys = new List<string> { "101", "103", "105" }; client.RemoveAll(delete_keys);
//13.清除全部数据 请小心 client.FlushAll();
付费内容,请联系本人QQ:1002453261
本文来自博客园,作者:明志德道,转载请注明原文链接:https://www.cnblogs.com/for-easy-fast/p/14527233.html