• Stars
    star
    1,907
  • Rank 24,185 (Top 0.5 %)
  • Language
    C#
  • License
    MIT License
  • Created over 7 years ago
  • Updated almost 2 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

.NET Core or .NET Framework 4.0+ client for Redis and Redis Sentinel (2.8) and Cluster. Includes both synchronous and asynchronous clients.

Features

  • CSRedisClient and RedisHelper Keep all method names consistent with redis-cli

  • Support geo type commands (redis-server 3.2 or above is required)

  • Support Redis Cluster redis-trib.rb

  • Support Redis Sentinel and master-slave

  • Supports stream type commands (requires redis-server 5.0 and above)

Package Name NuGet Downloads
CSRedisCore nuget stats
Caching.CSRedis nuget stats IDistributedCache

dotnet add package CSRedisCore

Single machine redis

var csredis = new CSRedis.CSRedisClient("127.0.0.1:6379,password=123,defaultDatabase=13,prefix=my_");
Parameter Default Explain
user <Empty> Redis server user (redis 6.0+)
password <Empty> Redis server password
defaultDatabase 0 Redis server database
asyncPipeline false The asynchronous method automatically uses pipeline, and the 10W concurrent time is 450ms (welcome to feedback)
poolsize 50 Connection pool size
idleTimeout 20000 Idle time of elements in the connection pool (MS), suitable for connecting to remote redis server
connectTimeout 5000 Connection timeout (MS)
syncTimeout 10000 Send / receive timeout (MS)
preheat 5 Preheat connections, receive values such as preheat = 5 preheat 5 connections
autoDispose true Follow system exit event to release automatically
ssl false Enable encrypted transmission
testcluster true 是否尝试集群模式,阿里云、腾讯云集群需要设置此选项为 false
tryit 0 Execution error, retry attempts
name <Empty> Connection name, use client list command to view
prefix <Empty> key前辍,所有方法都会附带此前辍,csredis.Set(prefix + "key", 111);

IPv6: [fe80::b164:55b3:4b4f:7ce6%15]:6379

Redis Sentinel

var csredis = new CSRedis.CSRedisClient("mymaster,password=123,prefix=my_", 
  new [] { "192.169.1.10:26379", "192.169.1.11:26379", "192.169.1.12:26379" });

Read only: new CSRedisClient("mymaster,password=123", new [] { Sentinels }, false)

Redis Cluster

假设你已经配置好 redis-trib 集群,定义一个【普通模式】的 CSRedisClient 对象,它会根据 redis-server 返回的 MOVED | ASK 错误记录slot,自动增加节点 Nodes 属性。

127.0.0.1:6379,password=123,defaultDatabase=0,poolsize=50,prefix=

其他节点在运行过程中自动增加,确保每个节点密码一致。

警告:本模式与【分区模式】同时使用时,切记不可设置“prefix=key前辍”(或者全部设置成一样),否则会导致 keySlot 计算结果与服务端不匹配,无法记录 slotCache。

注意:官方集群不支持多 keys 的命令、【管道】、Eval(脚本)等众多杀手级功能。

IDistributedCache

dotnet add package Caching.CSRedis

RedisHelper.Initialization(csredis);
services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));

Note: CSRedisClient is singleton, RedisHelper static class is recommended

RedisHelper.Set("test1", "123123", 60);
RedisHelper.Get("test1");
//The method name is the same as the command of redis cli

Operate on multiple databases

var connectionString = "127.0.0.1:6379,password=123,poolsize=10";
var redis = new CSRedisClient[14]; //Singleton
for (var a = 0; a< redis.Length; a++) 
  redis[a] = new CSRedisClient(connectionString + ",defaultDatabase=" + a);

redis[1].Get("test1");

Multiple RedisHelper

public abstract class MyHelper1 : RedisHelper<MyHelper1> {}
public abstract class MyHelper2 : RedisHelper<MyHelper2> {}

MyHelper1.Initialization(new CSRedisClient("...."));
MyHelper2.Initialization(new CSRedisClient("...."));

Subscribe/Publish

//Native subscribe
RedisHelper.Subscribe(
  ("chan1", msg => Console.WriteLine(msg.Body)),
  ("chan2", msg => Console.WriteLine(msg.Body)));

RedisHelper.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" 订阅全部节点时,需要解决同一条消息不可执行多次

RedisHelper.Publish("chan1", "123123123");

参考资料:【由浅至深】redis 实现发布订阅的几种方式

CacheShell

//不加缓存的时候,要从数据库查询
var t1 = Test.Select.WhereId(1).ToOne();

//一般的缓存代码,如不封装还挺繁琐的
var cacheValue = RedisHelper.Get("test1");
if (!string.IsNullOrEmpty(cacheValue)) {
	try {
		return JsonConvert.DeserializeObject(cacheValue);
	} catch {
		//出错时删除key
		RedisHelper.Remove("test1");
		throw;
	}
}
var t1 = Test.Select.WhereId(1).ToOne();
RedisHelper.Set("test1", JsonConvert.SerializeObject(t1), 10); //缓存10秒

//使用缓存壳效果同上,以下示例使用 string 和 hash 缓存数据
var t1 = RedisHelper.CacheShell("test1", 10, () => Test.Select.WhereId(1).ToOne());
var t2 = RedisHelper.CacheShell("test", "1", 10, () => Test.Select.WhereId(1).ToOne());
var t3 = RedisHelper.CacheShell("test", new [] { "1", "2" }, 10, notCacheFields => new [] {
  ("1", Test.Select.WhereId(1).ToOne()),
  ("2", Test.Select.WhereId(2).ToOne())
});

Pipeline

使用管道模式,打包多条命令一起执行,从而提高性能。

var ret1 = RedisHelper.StartPipe(p => p.Set("a", "1").Get("a"));

Benchmark

100,000 operations

StackExchange.Redis StringSet:7882ms
CSRedisCore Set:6101ms
-------------------
StackExchange.Redis StringGet:7729ms
CSRedisCore Get:5762ms
-------------------
StackExchange.Redis StringSetAsync:8094ms
CSRedisCore SetAsync:6315ms
-------------------
StackExchange.Redis StringGetAsync:7986ms
CSRedisClient GetAsync:4931ms
CSRedisCore GetAsync:5960ms
-------------------
CSRedisCore SetAsync(Task.WaitAll):559ms
StackExchange.Redis StringSetAsync (concurrent Task.WaitAll):172ms
-------------------
CSRedisCore GetAsync(Task.WaitAll):435ms
StackExchange.Redis StringGetAsync (concurrent Task.WaitAll):176ms

💕 Donation (捐赠)

感谢你的打赏

Thank

Original open source project: https://github.com/ctstone/csredis

More Repositories

1

FreeIM

.NETCore websocket 实现简易、高性能、集群即时通讯组件,支持点对点通讯、群聊通讯、上线下线事件消息等众多实用性功能.
C#
1,223
star
2

FreeRedis

🦄 FreeRedis is .NET40+ redis client. supports cluster, sentinel, master-slave, pub-sub, lua, pipeline, transaction, streams, client-side-caching, and pooling.
C#
903
star
3

dotnetGen_mysql

.NETCore + Mysql 生成器
C#
242
star
4

FreeSql.Tools

FreeSql 工具包,包括生成器等
C#
212
star
5

FreeSql.AdminLTE

这是一个 .NETCore MVC 中间件,基于 AdminLTE 前端框架动态产生 FreeSql 实体的增删查改界面。
C#
166
star
6

FreeScheduler

轻量化定时任务调度,支持临时的延时任务和重复循环任务(可持久化),可按秒,每天/每周/每月固定时间,自定义间隔执行,支持 .NET Core 2.1+、.NET Framework 4.0+ 运行环境。
C#
164
star
7

dotnetGen_sqlserver

.NETCore + SqlServer 生成器
C#
149
star
8

SafeObjectPool

应用场景:连接池,资源池等等
C#
112
star
9

IdleBus

IdleBus 空闲对象管理容器,有效组织对象重复利用,自动创建、销毁,解决【实例】过多且长时间占用的问题。
C#
107
star
10

dotnetGen_postgresql

.NETCore + PostgreSQL 生成器
C#
94
star
11

NPinyin

拼音汉字转换 .NETCore 版本
C#
80
star
12

FreeSql.Cloud

提供跨数据库访问,分布式事务TCC、SAGA解决方案。
C#
65
star
13

Microsoft.Extensions.Caching.CSRedis

分布式缓存,替代 Microsoft.Extensions.Caching.Redis
C#
44
star
14

FreeSql.DbContext

FreeSql 扩展包,实现真正的 ORM,Repository DbContext UnitOfWork 实现。
C#
41
star
15

FreeSql.DynamicProxy

The dynamic proxy on The .NetCore or .NetFramework4.0+. Support asynchronous method interception, Method parameter interception, Property interception, multiple intercepts, dependency injection and inversion of control
C#
38
star
16

TcpClientHttpRequest

基于 TcpClient 现实的 http请求库,编写于2007年做了几年数据采集工作。
C#
34
star
17

NJob

超级轻便的调度器
C#
30
star
18

FreeSql.Wiki.VuePress

FreeSql wiki 文档采用 vuepress
Dockerfile
30
star
19

MySocket

Socket服务端与客户端的封装(IOCP、EPOLL),支持.NETCore
C#
28
star
20

WorkQueue

超级轻便的线程队列工作器
C#
25
star
21

ojbk

模块化的单体应用项目
JavaScript
21
star
22

dotnetGen

.NET Framework 3.0 + SqlServer 生成器(停止更新)
C#
17
star
23

genms_shop

.NETCore 快速开发做一个简易商城
JavaScript
13
star
24

FreeSql.Connection.Extensions

Mysql, postgresql, sqlserver, Oracle and SQLite connection object extension methods.
C#
10
star
25

dng.Mysql

dotnetgen_mysql生成器所需MySql.Data的基础封装
C#
6
star
26

bmw.js

JavaScript
6
star
27

robot_test

简易任务调度
C#
6
star
28

dotnetGen_demo

dotnetGen 生成后的项目示例
C#
5
star
29

dng.Mssql

dotnetgen_sqlserver生成器所需System.Data.SqlClient的基础封装
C#
4
star
30

oss_signature

阿里云OSS服务端签名后直传,模仿官方get.php代码实现
C#
4
star
31

Spider

爬虫工具,.NET2.0实现
C#
4
star
32

AdminBlazor

AdminBlazor 是一款 Blazor SSR 后台管理项目,支持 RABC 权限菜单/按钮,支持一对一、一对多、多对多代码生成 .razor 界面。
HTML
4
star
33

dng.Pgsql

dotnetgen_postgresql生成器所需npgsql的基础封装
C#
3
star
34

dng.Template

模板引擎,不再使用(作纪念)
C#
3
star
35

cnodejs_netcore

.NETCore + MySql 实现的 cnodejs.org
JavaScript
2
star