NuGet 直接搜索安装 ServiceStack.Redis
代码如下:
using ServiceStack.Redis; using System; namespace redisDemo { class Program { static void Main(string[] args) { RedisClient redisClient = new RedisClient("114.67.234.9", 6379);//redis服务IP和端口 Console.WriteLine(redisClient.Get<string>("lina")); Console.ReadKey(); } } }
超过6000次 提示收费
Helper:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Cryptography; using System.Text; namespace ServiceStack.Redis { public class RedisHelper : IDisposable { /// <summary> /// 主服务器IP,写操作 /// </summary> //public static string MasterIP = "192.168.10.21";//"127.0.0.1"; public string MasterIP = RedisHelperConfig.MasterIP; /// <summary> /// 端口 /// </summary> public int MasterPort = RedisHelperConfig.MasterPort; /// <summary> /// 数据库 0-15,默认为0 /// </summary> public long Database = RedisHelperConfig.Database; /// <summary> /// 从服务器IP,读操作 /// </summary> //public static string SlaverIP = "192.168.10.13";//"127.0.0.1"; public string SlaverIP = RedisHelperConfig.SlaverIP; /// <summary> /// 端口 /// </summary> public int SlaverPort = RedisHelperConfig.SlaverPort; /// <summary> /// 默认KEY 存活时间 /// </summary> public static int KeyLiveSecond = RedisHelperConfig.KeyLiveSecond; RedisClient master = null; RedisClient slaver = null; public RedisHelper() { slaver = new RedisClient(SlaverIP, SlaverPort, null, Database); master = new RedisClient(MasterIP, MasterPort, null, Database); } public RedisHelper(string _MasterIP, int _MasterPort, string _SlaverIP, int _SlaverPort, long _Database) { MasterIP = _MasterIP; MasterPort = _MasterPort; SlaverIP = _SlaverIP; SlaverPort = _SlaverPort; Database = _Database; slaver = new RedisClient(SlaverIP, SlaverPort, null, Database); master = new RedisClient(MasterIP, MasterPort, null, Database); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { Quit(); } } #region 过期操作 /// <summary> /// 获取剩余存货秒 /// </summary> /// <param name="key"></param> /// <returns></returns> public long GetTimeToLive(string key) { long ttlSecs = slaver.Ttl(key); return ttlSecs; } /// <summary> /// KEY 存活到 某个时间点 /// </summary> /// <param name="key"></param> /// <param name="expireAt"></param> /// <returns></returns> public bool SetKeyLiveAt(string key, DateTime expireAt) { return master.ExpireEntryAt(key, expireAt); } /// <summary> /// 设置 key存活 second 秒 /// </summary> /// <param name="key"></param> /// <param name="second"></param> /// <returns></returns> public bool SetKeyLiveAt(string key, int second) { return master.Expire(key, second); } /// <summary> /// 设置 key存活 TimeSpan秒 /// </summary> /// <param name="key"></param> /// <param name="ts"></param> /// <returns></returns> public bool SetKeyLiveAt(string key, TimeSpan ts) { return master.Expire(key, (int)ts.TotalSeconds); } #endregion #region 基础操作 /// <summary> /// 更换数据库 /// </summary> /// <param name="db"></param> public void ChangeDB(long db) { Database = db; master.Db = Database; slaver.Db = Database; } /// <summary> /// 是否包含key的值 /// </summary> /// <param name="key"></param> /// <returns></returns> public bool ContainsKey(string key) { return slaver.ContainsKey(key); } /// <summary> /// 移除key的信息 /// </summary> /// <param name="key"></param> /// <returns></returns> public bool Remove(string key) { return master.Remove(key); } /// <summary> /// 移除多个key值 /// </summary> /// <param name="keys"></param> /// <returns></returns> public bool RemoveEntry(params string[] keys) { return master.RemoveEntry(keys); } /// <summary> /// 重命名 /// </summary> /// <param name="fromName"></param> /// <param name="toName"></param> public void RenameKey(string fromName, string toName) { master.RenameKey(fromName, toName); } /// <summary> /// 随便取一个key值 /// </summary> /// <returns></returns> public string GetRandomKey() { return slaver.GetRandomKey(); } /// <summary> /// 关闭连接 /// </summary> public void Quit() { slaver.Quit(); master.Quit(); } #endregion #region 基础类型 String int Decimal DateTime /// <summary> /// 通过匹配方式获取Key信息 /// </summary> /// <param name="keyPattern"> /// h?llo 匹配 hello /// h*llo 匹配 hllo 和 heeeeello 等 /// h[ae]llo 匹配 hello 和 hallo ,但不匹配 hillo /// </param> /// <returns></returns> public List<string> GetKeysPattern(string keyPattern) { List<string> result = new List<string>(); byte[][] rlt = slaver.Keys(keyPattern); //result = slaver.Get<string>(key); for (int i = 0; i < rlt.Length; i++) { result.Add(FromUtf8Bytes(rlt[i])); } return result; } public string GetKeyString(string key) { string result = ""; result = slaver.Get<string>(key); return result; } public int? GetKeyInt(string key) { int? result = 0; result = slaver.Get<int?>(key); return result; } public Decimal? GetKeyDecimal(string key) { Decimal? result = 0M; result = slaver.Get<Decimal?>(key); return result; } public DateTime? GetKeyDateTime(string key) { DateTime? result = null; result = slaver.Get<DateTime?>(key); return result; } public long SetKey(string Key, string Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.Set<string>(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } public long SetKey(string Key, int Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.Set<int>(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } public long SetKey(string Key, decimal Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.Set<decimal>(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } public long SetKey(string Key, DateTime Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.Set<DateTime>(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } #endregion #region List public long GetListLength(string key) { long result = 0; result = slaver.LLen(key); return result; } public List<string> GetList(string key) { List<string> result = null; result = slaver.GetAllItemsFromList(key); return result; } public List<string> GetList(string key, int bgnIndex, int endIndex) { List<string> result = null; result = slaver.GetRangeFromList(key, bgnIndex, endIndex); return result; } /// <summary> /// 返回第index个元素 默认从0开始,-1为倒数第一个 /// </summary> /// <param name="key"></param> /// <param name="index"></param> /// <returns></returns> public string GetListIndex(string key, Int32 index) { string result = ""; result = FromUtf8Bytes(slaver.LIndex(key, index)); return result; } /// <summary> /// List从右侧添加对象 /// </summary> /// <param name="Key"></param> /// <param name="Value"></param> /// <returns></returns> public long ListAddItemR(string Key, string Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.AddItemToList(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } /// <summary> /// List从右侧添加对象集合 /// </summary> /// <param name="Key"></param> /// <param name="Value"></param> /// <returns></returns> public long ListAddRangeR(string Key, List<string> Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.AddRangeToList(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } /// <summary> /// List从左侧添加对象集合 /// </summary> /// <param name="Key"></param> /// <param name="Value"></param> /// <returns></returns> public long ListAddItemL(string Key, string Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.PrependItemToList(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } /// <summary> /// List从左侧添加对象集合 /// </summary> /// <param name="Key"></param> /// <param name="Value"></param> /// <returns></returns> public long ListAddRangeL(string Key, List<string> Value, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.PrependRangeToList(Key, Value); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } /// <summary> /// 清空key 的所有元素 /// </summary> /// <param name="Key"></param> /// <returns></returns> public long ListRemoveAll(string Key, int second = 0) { Stopwatch sw = new Stopwatch(); sw.Start(); master.RemoveAllFromList(Key); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return sw.ElapsedMilliseconds; } /// <summary> /// 移除并返回列表 key 的头元素 /// </summary> /// <param name="Key"></param> /// <returns></returns> public string ListLPOP(string Key, int second = 0) { string result = ""; Stopwatch sw = new Stopwatch(); sw.Start(); result = FromUtf8Bytes(master.LPop(Key)); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return result; } /// <summary> /// 移除并返回列表 key 的尾元素 /// </summary> /// <param name="Key"></param> /// <returns></returns> public string ListRPOP(string Key, int second = 0) { string result = ""; Stopwatch sw = new Stopwatch(); sw.Start(); result = FromUtf8Bytes(master.RPop(Key)); if (second != 0) { SetKeyLiveAt(Key, second); } sw.Stop(); return result; } #endregion #region Convert public byte[] ToUtf8Bytes(string value) { return Encoding.UTF8.GetBytes(value); } public string FromUtf8Bytes(byte[] bytes) { if (bytes != null) { return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } return null; } #endregion } }
声明一个客户端对象:
protected RedisClient Redis = new RedisClient("127.0.0.1", 6379);//redis服务IP和端口
一 .基本KEY/VALUE键值对操作:
1. 添加/获取:
List<string> storeMembers = new List<string>(); storeMembers.ForEach(x => Redis.AddItemToList("test", x)); //注:也可直接使用AddRangeToList方法将一组数据装入如: Redis.AddRangeToList("testt", storeMembers);
2. 获取数据
var members = Redis.GetAllItemsFromList("test"); members.ForEach(s => Response.Write("<br/>test :" + s));
3. 获取指定索引位置数据
var item = Redis.GetItemFromList("test", 2);
4. 移除:
var list = Redis.Lists["test"]; list.Clear();//清空 list.Remove("two");//移除指定键值 list.RemoveAt(2);//移除指定索引位置数据
二.存储对象:
[Serializable] public class UserInfo { public long Id { set; get; } public string UserName { get; set; } public int Age { get; set; } }
1.通常方式(底层使用json序列化):
Redis.Set<UserInfo>("userinfo", new UserInfo() { UserName = "李四", Age = 45 }); UserInfo userinfo = Redis.Get<UserInfo>("userinfo");
注:当然上面方式也适合于基本类型,如:
Redis.Set<int>("my_age", 12);//或Redis.Set("my_age", 12); int age = Redis.Get<int>("my_age");
2.object序列化方式存储:
var ser = new ObjectSerializer(); //位于namespace ServiceStack.Redis.Support; bool result = Redis.Set<byte[]>("userinfo", ser.Serialize(new UserInfo() { UserName = "张三", Age = 12 })); UserInfo userinfo = ser.Deserialize(Redis.Get<byte[]>("userinfo")) as UserInfo; //也支持列表 List<UserInfo> userinfoList = new List<UserInfo>(); userinfoList.Add(new UserInfo() { UserName = "pool_daizhj", Age = 1 }); userinfoList.Add(new UserInfo() { UserName = "pool_daizhj1", Age = 2 }); Redis.Set<byte[]>("userinfolist_serialize", ser.Serialize(userinfoList)); List<UserInfo> userList = ser.Deserialize(Redis.Get<byte[]>("userinfolist_serialize")) as List<UserInfo>;
需要说明的是在测试过程中发现JSON序列化的效率要比object序列化高一些。
三.存储表格对象,比如:
using (var redisUsers = Redis.As<UserInfo>()) { redisUsers.Store(new UserInfo { Id = redisUsers.GetNextSequence(), UserName = "test1", Age = 22 }); redisUsers.Store(new UserInfo { Id = redisUsers.GetNextSequence(), UserName = "test2", Age = 23 }); var allUsers = redisUsers.GetAll();//就像操作ado对象一样,可以进行CRUD等操作 }
四.使用客户端链接池模式提升链接速度:
public static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts) { //支持读写分离,均衡负载 return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig { MaxWritePoolSize = 5,//“写”链接池链接数 MaxReadPoolSize = 5,//“读”链接池链接数 AutoStart = true, }); }
声明链接池对象(这里只使用一个redis服务端):
PooledRedisClientManager prcm = CreateManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" }); List<UserInfo> userinfoList = new List<UserInfo>(); userinfoList.Add(new UserInfo() { UserName = "pool_daizhj", Age = 1 }); userinfoList.Add(new UserInfo() { UserName = "pool_daizhj1", Age = 2 });
从池中获取一个链接:
using (IRedisClient Redis = prcm.GetClient()) { Redis.Set("userinfolist", userinfoList); List<UserInfo> userList = Redis.Get<List<UserInfo>>("userinfolist"); }
注:
如只想使用长链接而不是链接池的话,可以直接将下面对象用static方式声明即可:
protected static RedisClient Redis = new RedisClient("127.0.0.1", 6379);
这样在redis服务端显示只有一个客户链接
参考:
http://www.cnblogs.com/qtqq/p/5951201.html
https://www.cnblogs.com/xinzheng/p/6063505.html
原文地址:https://www.cnblogs.com/xiaoshi657/p/9295932.html
时间: 2024-11-06 03:34:19