现在流行的redis连接客户端有StackExchange.Redis和ServiceStack.Redis,为什么选择csredis而不是这两个?
-
.net 最有名望的 ServiceStack.Redis 早已沦为商业用途,在 .NETCore 中使用只能充值;
-
后来居上的 StackExchange.Redis 虽然能用,但线上各种 Timeout 错误把人坑到没脾气,两年多两年多两年多都不解决,最近发布的 2.0 版本不知道是否彻底解决了底层。
-
csredis支持.net40/.net45/.netstandard2.0,基本上满足了常见运行平台,而上面两个基本已经放弃.net40了。.
-
csredis所有方法名与redis-cli保持一持,很容易上手!!!
环境:
-
redis6.0.6
-
window 10
-
vs2019
-
csredis3.6.5(https://github.com/2881099/csredis)
-
.net4/.net 4.5/.netcore 3.1
csredis 源码地址:https://github.com/2881099/csredis
以windows服务安装Redis方法:
下载Redis服务安装包:https://github.com/tporadowski/redis/releases。
下载完成后直接点击.exe下一步下一步OK。安装完后我们会在windows服务中找到Redis Service服务。注意启动服务后在进行相关测试。
1.在.net项目中引入CSRedisCore
包安装命令:
Install-Package CSRedisCore -Version 3.6.5
2.使用:
//初始化RedisHelper对象
var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379, defaultDatabase = 0, poolsize = 500, ssl = false, writeBuffer = 10240");
RedisHelper.Initialization(csredis);
//-------------字符串(string)----------------
// 添加字符串键-值对
csredis.Set("hello", "1");
csredis.Set("world", "2");
csredis.Set("hello", "3");
// 根据键获取对应的值
csredis.Get("hello");
// 移除元素
csredis.Del("world");
/* 数值操作 */
csredis.Set("num-key", "24");
// value += 5
csredis.IncrBy("num-key",5);
// output -> 29
// value -= 10
csredis.IncrBy("num-key", -10);
// output -> 19
/* 字节串操作 */
csredis.Set("string-key", "hello ");
// 在指定key的value末尾追加字符串
csredis.Append("string-key", "world");
// output -> "hello world"
// 获取从指定范围所有字符构成的子串(start:3,end:7)
csredis.GetRange("string-key",3,7)
// output -> "lo wo"
// 用新字符串从指定位置覆写原value(index:4)
csredis.SetRange("string-key", 4, "aa");
// output -> "hellaaword"
//-----------------列表(list)----------------
// 从右端推入元素
csredis.RPush("my-list", "item1", "item2", "item3", "item4");
// 从右端弹出元素
csredis.RPop("my-list");
// 从左端推入元素
csredis.LPush("my-list","LeftPushItem");
// 从左端弹出元素
csredis.LPop("my-list");
// 遍历链表元素(start:0,end:-1即可返回所有元素)
foreach (var item in csredis.LRange("my-list", 0, -1))
{
Console.WriteLine(item);
}
// 按索引值获取元素(当索引值大于链表长度,返回空值,不会报错)
Console.WriteLine($"{csredis.LIndex("my-list", 1)}");
// 修剪指定范围内的元素(start:4,end:10)
csredis.LTrim("my-list", 4, 10);
// 将my-list最后一个元素弹出并压入another-list的头部
csredis.RPopLPush("my-list", "another-list");
//------------------集合(set)----------------
// 实际上只插入了两个元素("item1","item2")
csredis.SAdd("my-set", "item1", "item1", "item2");
// 集合的遍历
foreach (var member in csredis.SMembers("my-set"))
{
Console.WriteLine($"集合成员:{member.ToString()}");
}
// 判断元素是否存在
string member = "item1";
Console.WriteLine($"{member}是否存在:{csredis.SIsMember("my-set", member)}");
// output -> True
// 移除元素
csredis.SRem("my-set", member);
Console.WriteLine($"{member}是否存在:{csredis.SIsMember("my-set", member)}");
// output -> False
// 随机移除一个元素
csredis.SPop("my-set");
csredis.SAdd("set-a", "item1", "item2", "item3","item4","item5");
csredis.SAdd("set-b", "item2", "item5", "item6", "item7");
// 差集
csredis.SDiff("set-a", "set-b");
// output -> "item1", "item3","item4"
// 交集
csredis.SInter("set-a", "set-b");
// output -> "item2","item5"
// 并集
csredis.SUnion("set-a", "set-b");
// output -> "item1","item2","item3","item4","item5","item6","item7"
//------------------散列(hashmap)----------------
// 向散列添加元素
csredis.HSet("ArticleID:10001", "Title", "了解简单的Redis数据结构");
csredis.HSet("ArticleID:10001", "Author", "xscape");
csredis.HSet("ArticleID:10001", "PublishTime", "2019-01-01");
// 根据Key获取散列中的元素
csredis.HGet("ArticleID:10001", "Title");
// 获取散列中的所有元素
foreach (var item in csredis.HGetAll("ArticleID:10001"))
{
Console.WriteLine(item.Value);
}
//HMGet和HMSet是他们的多参数版本,一次可以处理多个键值对
var keys = new string[] { "Title","Author","publishTime"};
csredis.HMGet("ID:10001", keys);
//和处理字符串一样,我们也可以对散列中的值进行自增、自减操作,原理同字符串是一样的
csredis.HSet("ArticleID:10001", "votes", "257");
csredis.HIncrBy("ID:10001", "votes", 40);
// output -> 297
//------------------有序集合----------------
// 向有序集合添加元素
csredis.ZAdd("Quiz", (79, "Math"));
csredis.ZAdd("Quiz", (98, "English"));
csredis.ZAdd("Quiz", (87, "Algorithm"));
csredis.ZAdd("Quiz", (84, "Database"));
csredis.ZAdd("Quiz", (59, "Operation System"));
//返回集合中的元素数量
csredis.ZCard("Quiz");
// 获取集合中指定范围(90~100)的元素集合
csredis.ZRangeByScore("Quiz",90,100);
// 获取集合所有元素并升序排序
csredis.ZRangeWithScores("Quiz", 0, -1);
// 移除集合中的元素
csredis.ZRem("Quiz", "Math");
//Key的过期
redis.Set("MyKey", "hello,world");
Console.WriteLine(redis.Get("MyKey"));
// output -> "hello,world"
redis.Expire("MyKey", 5); // key在5秒后过期,也可以使用ExpireAt方法让它在指定时间自动过期
Thread.Sleep(6000); // 线程暂停6秒
Console.WriteLine(redis.Get("MyKey"));
// output -> ""
https://www.cnblogs.com/xscape/p/10208638.html
3.高级玩法:发布订阅
//普通订阅
rds.Subscribe(
("chan1", msg => Console.WriteLine(msg.Body)),
("chan2", msg => Console.WriteLine(msg.Body)));
//模式订阅(通配符)
rds.PSubscribe(new[] { "test*", "*test001", "test*002" }, msg => {
Console.WriteLine($"PSUB {msg.MessageId}:{msg.Body} {msg.Pattern}: chan:{msg.Channel}");
});
//模式订阅已经解决的难题:
//1、分区的节点匹配规则,导致通配符最大可能匹配全部节点,所以全部节点都要订阅
//2、本组 "test*", "*test001", "test*002" 订阅全部节点时,需要解决同一条消息不可执行多次
//发布
rds.Publish("chan1", "123123123");
//无论是分区或普通模式,rds.Publish 都可以正常通信
4.高级玩法:缓存壳
//不加缓存的时候,要从数据库查询
var t1 = Test.Select.WhereId(1).ToOne();
//一般的缓存代码,如不封装还挺繁琐的
var cacheValue = rds.Get("test1");
if (!string.IsNullOrEmpty(cacheValue)) {
try {
return JsonConvert.DeserializeObject(cacheValue);
} catch {
//出错时删除key
rds.Remove("test1");
throw;
}
}
var t1 = Test.Select.WhereId(1).ToOne();
rds.Set("test1", JsonConvert.SerializeObject(t1), 10); //缓存10秒
//使用缓存壳效果同上,以下示例使用 string 和 hash 缓存数据
var t1 = rds.CacheShell("test1", 10, () => Test.Select.WhereId(1).ToOne());
var t2 = rds.CacheShell("test", "1", 10, () => Test.Select.WhereId(1).ToOne());
var t3 = rds.CacheShell("test", new [] { "1", "2" }, 10, notCacheFields => new [] {
("1", Test.Select.WhereId(1).ToOne()),
("2", Test.Select.WhereId(2).ToOne())
});
5.高级玩法:管道
使用管道模式,打包多条命令一起执行,从而提高性能。
var ret1 = rds.StartPipe().Set("a", "1").Get("a").EndPipe();
var ret2 = rds.StartPipe(p => p.Set("a", "1").Get("a"));
var ret3 = rds.StartPipe().Get("b").Get("a").Get("a").EndPipe();
//与 rds.MGet("b", "a", "a") 性能相比,经测试差之毫厘
6.高级玩法:多数据库
var connectionString = "127.0.0.1:6379,password=123,poolsize=10,ssl=false,writeBuffer=10240,prefix=key前辍";
var redis = new CSRedisClient[14]; //定义成单例
for (var a = 0; a< redis.Length; a++) redis[a] = new CSRedisClient(connectionString + "; defualtDatabase=" + a);
//访问数据库1的数据
redis[1].Get("test1");