2881099 / csredis Goto Github PK
View Code? Open in Web Editor NEW.NET Core or .NET Framework 4.0+ client for Redis and Redis Sentinel (2.8) and Cluster. Includes both synchronous and asynchronous clients.
License: MIT License
.NET Core or .NET Framework 4.0+ client for Redis and Redis Sentinel (2.8) and Cluster. Includes both synchronous and asynchronous clients.
License: MIT License
class Program
{
static CSRedis.CSRedisClient client = new CSRedis.CSRedisClient("ssssssss,defaultDatabase=50,poolsize=50,ssl=false,writeBuffer=10240,prefix=tt");
static void Main(string[] args)
{
RedisHelper.Initialization(client,
value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
for (int i = 0; i < 1000; i++)
{
Thread t = new Thread(new ThreadStart(Pro));
t.Start();
}
Console.ReadKey();
}
static void Pro()
{
for (int i = 0; i < 4; i++)
{
RedisHelper.Instance.Get("sdfsdfsdfsdf");
}
}
}
模拟1000个并发来测试。总是会提示 链接远程关闭。
redis Hset :如果字段是哈希表中的一个新建字段,并且值设置成功,返回 1 。 如果哈希表中域字段已经存在且旧值已被新值覆盖,返回 0
更新的时候,程序里也和1比较了。
这里可能是为了性能,而忽略了
如何开启一个事务 如 pipeline 功能
调用RedisHelper.Keys频繁抛出异常.
System.IO.EndOfStreamException: Unexpected end of stream; expected type 'MultiBulk'
at CSRedis.Internal.IO.RedisReader.ExpectType(RedisMessage expectedType)
at CSRedis.Internal.Commands.RedisArray.Generic`1.Parse(RedisReader reader)
at CSRedis.Internal.RedisConnector.Call[T](RedisCommand`1 command)
at CSRedis.RedisClient.Write[T](RedisCommand`1 command)
at CSRedis.RedisClient.Keys(String pattern)
at CSRedis.CSRedisClient.Keys(String pattern)
at RedisHelper.Keys(String pattern)
at NbCRM.Account.TokenHelper.GetXTokenFromRedis(String plainToken) in C:\Projects\NbCRM\NbCRM.Account\src\NbCRM.Account\Helper\TokenHelper.cs:line 75
at NbCRM.Account.Impl.UserServiceImpl.GetUserPath(Querys request, ServerCallContext context) in C:\Projects\NbCRM\NbCRM.Account\src\NbCRM.Account\Impl\UserServiceImpl.cs:line 750
at Grpc.Core.Internal.UnaryServerCallHandler`2.<>c__DisplayClass4_2.<<HandleCall>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
public static T GetIfNotExist<T>(string Key, Func<T> Func, int ExpireSecond = 3600) where T : class
{
var t = Get<T>(Key) ?? Func();
Set(Key, t, ExpireSecond);
return t;
}
作为缓存库使用的话用的非常多....
我查了服务器用的是标准**时间、Redis的时间也是同步的。但是我14:30设置当天17:30过期的key、生成出来的TTL却有11个小时。
\CSRedis\Internal\Commands\RedisArray.cs
第 82 行,在:
long count = reader.ReadInt(false);
下面增加:
if (count == -1) return default(T);
使用 BLPop 命令 阻塞超时后 reader.ReadInt(false) 会返回 -1。
感谢快速迭代。上午题的问题已经解决。
但是又发现新的问题了。(捂脸。。。我都不好意思在博客下留言了
50个线程跑(应该不过分吧?)
在redis重启后,直接卡主不动了。
30个重启一次还可以正常使用,但是停止或多次后也出现锁住的情况。
for (int i = 0; i < 50; i++)
{
new Thread(() => {
while (true) {
Task.Run(async () => {
string aaa = "aaa undefined";
try {
aaa = await RedisHelper.CacheShellAsync("keyAsync", "1", 1000,
async () => await Task.FromResult("Async Cache" + DateTime.Now.ToLongTimeString())); ;
} catch (Exception ex) {
Console.WriteLine(ex.Message);
}
Console.WriteLine(DateTime.Now.ToLongTimeString() + " : " + aaa);
}).Wait();
Thread.CurrentThread.Join(500);
}
}).Start();
}
仅测了一次30并发,重启后没有恢复。
你好,按照实例在Startup中配置:
var csredis= new CSRedis.CSRedisClient("172.16.8.222:6379,password=,defaultDatabase=11,poolsize=10,ssl=false,writeBuffer=10240");
RedisHelper.Initialization(csredis,
value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
//注入Redis缓存
services.AddSingleton<IDistributedCache>(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
之后,我要操作的数据,分别在同一个Redis服务器上的不同的db中,要在代码中切换数据库,请问应该如何操作?谢谢
代码如下:
var list = await RedisHelper.CacheShellAsync(_key_bank_list, 60 * 60 * 24 * 7, () => bankdal.Banks());
其中bankdal.Banks()是一个异步方法,使用的是Dapper的QueryAsync方法读取数据库。
使用Postman进行提交测试,单步跟踪,到CacheShellAsync之后,从数据库中读取完数据,就直接跳到Startup.cs中注入CSRedis位置:
RedisHelper.Initialization(csredis,
value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
再之后就看不到其他的执行,而Postman还在等待接口返回数据,一直处在“loading”状态;如果Redis中有数据的话,就不会有这问题。应该是异步写Redis出的问题,麻烦修复一下,谢谢。
好像没有把SetNx的方法暴露出来
在使用csredis获取sentinel时产生运行时异常,调查问题最后发现是获取sentinel的s-down-time配置参数存在问题。在sentinel集群中并非每个sentinel都能获取到这个参数,获取不到就抛出异常了。
获取s-down-time的代码在Types.cs文件中,RedisSentinelInfo类的构造函数:
public RedisSentinelInfo(SerializationInfo info, StreamingContext context): base(info, context)
SDownTime = info.GetInt64("s-down-time");
由于info中不存在s-down-time,在此出现了异常。
从SerializationInfo中安全获取某个值的方法:
/// <summary>
/// Get a value from an instance of the SerializationInfo
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="info"></param>
/// <param name="key"></param>
/// <returns></returns>
private T GetSerializationItemValue<T>(SerializationInfo info, string key)
{
foreach (SerializationEntry entry in info)
{
if (entry.Name == key)
{
return (T)Convert.ChangeType(entry.Value, typeof(T), System.Globalization.CultureInfo.InvariantCulture);
}
}
return default(T);
}
如果对应的值不存在,则返回指定类型的默认值。
因此修改获取s-down-time的方法为:
var s_down_time = GetSerializationItemValue(info, "s-down-time");
SDownTime = s_down_time == 0 ? -1 : s_down_time;
//注册mvc分布式缓存
services.AddSingleton(new Microsoft.Extensions.Caching.Redis.CSRedisCache(RedisHelper.Instance));
这个 CSRedisCache指的是什么,从哪里来的呢,求解一下,谢谢!
怎么怎样切换数据库 # 多个数据库操作
比如,我现在设置key=aaa,value=bbb,600秒后过期,但是在过了320秒后,我要修改这个数据,key=aaa,value=abc,但是过期时间不改变(现在应该是280)。这个该如何操作呢?set方法有个默认值,如果不传递的话,会导致过期时间变更为-1
我使用这个方法去缓存大概400条数据时候,显示function or expression too complex near '[' " 这个错误,我的数据格式类似这种:[“1”,“json字符串”],麻烦跟踪下,谢谢!
CSRedis.RedisException:“NOAUTH Authentication required.”
您好,在Nuget上安装的csrediscore,使用时无法找到Microsoft.Extensions.Caching.Redis.CSRedisCache类,请问这个类在哪定义?
在实际使用中会经常性抛出Unexpected end of stream; expected type 'Bulk'异常和System.NotSupportedException异常,在压测时会周期性抛连接被重置异常,造成整个redis一直不可用,过一会又自己好了,使用的是单例模式,连接64个。
public static RedisStatus HMSet(string key, params object[] keyValues)
{
List<object> args = new List<object> { key };
for (int i = 0; i < keyValues.Length; i += 2)
{
if (keyValues[i] != null && keyValues[i + 1] != null)
args.AddRange(new[] { keyValues[i], keyValues[i + 1] });
}
return new RedisStatus("HMSET", args.ToArray());
}
HashSetNx 方法第三个参数value建议改进成string类型,容易造成误解,结果序列化结果不对,或者增加泛型支持
我这边测试程序用了 100 个并发,1秒发起一次,redis 连接池配置为 500 。不到一会连接池满,就会报 CSRedis.ConnectionPool.GetConnection 连接池获取超时(10秒)
使用的方式是用 RedisHelper.
使用LPush 可以插入数据 但是使用LPOP 或者 LRang 等功能时 返回的都是空值 这是为什么呢?
阿里云的 redis 服务。
写了一个测试应用,BRPop 超时时间 60秒,100个线程,全部阻塞结束后需要 135-144秒。
多个实例也是如此。
同一个机器多开测试应用仍然是 135-144秒完成,也就是说,每个进程都可以同时并发 30-50个 BRPop 链接。
多个客户机同时测试结果也是如此。
请问大佬,这个限制是如何产生的?有没有办法规避?
如果确定一定以及肯定非要有切换数据库的需求,请看以下代码:
......
下面的这段代码:
for (var a = 0; a< redis.Length; a++) redis[a] = new CSRedisClient(connectionString + "; defualtDatabase=" + a);
应该写成:
for (var a = 0; a< redis.Length; a++) redis[a] = new CSRedisClient(connectionString + ",defaultDatabase=" + a);
I want to know Open source license about the project , MIT Or GPL?
建议新增个RedisHelper.Set(string key,T obj)方法,里面进行序列化封装。
System.Exception: 【127.0.0.1:6379/0】状态不可用,等待后台检查程序恢复方可使用。Unexpected end of stream; expected type 'Status'
at SafeObjectPool.ObjectPool1.getFree(Boolean checkAvailable) at SafeObjectPool.ObjectPool
1.Get(Nullable1 timeout) at CSRedis.CSRedisClient.GetAndExecute[T](RedisClientPool pool, Func
2 handler, Int32 jump)
at CSRedis.CSRedisClient.ExecuteScalar[T](String key, Func`3 hander)
at CSRedis.CSRedisClient.Get(String key)
at RedisHelper.Get(String key)
3.0以前的版本没问题。
问题发现人:CosmoKey
感谢分享,已在使用。
线上有个需求,需要对Cache做熔断处理,在做测试期间发现:在网络不通的情况下(redis启动晚于客户端),使用RedisHelper.CacheShellAsync方法出现异常(System.IO.IOException: The operation is not allowed on non-connected sockets.)并无法被拦截。
测试代码:
try
{
await RedisHelper.CacheShellAsync("key", "1", 1000,
async () => await Task.FromResult("Cache" + DateTime.Now.ToLongTimeString()));
}
catch (Exception e)
{
}
希望能有更好的修复方案。
CSRedis.CSRedisClient Redis = RedisBase.RedisSentinelX;
var s1 = Redis.Increment(key1, numbers);
var s2 = Redis.Increment(key2, fees);
进行操作之后,如何释放Redis链接
来防止get connection error
///
大神,发布消息为什么加个{msgid}|
请教一下,RedisHelper初始化方式变了么?现在已经深度集成Json.net为序列化插件么?
还有以前的自定义序列化接口么?
我们之前使用 Jil 序列化,保留上一个版本的初始化接口就更好了
什么时候可以添加
core中使用一段时间不管web,再操作时总会报redis连接异常,不知道什么原因
linux下没发现这问题,iis里的很多这种错误
Unable to write data to the transport connection: 你的主机中的软件中止了一个已建立的连接。. System.IO.IOException: Unable to write data to the transport connection: 你的主机中的软件中止了一个已建立的连接。. ---> System.Net.Sockets.SocketException: 你的主机中的软件中止了一个已建立的连接。 at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size) --- End of inner exception stack trace --- at System.Net.Sockets.NetworkStream.Write(Byte[] buffer, Int32 offset, Int32 size) at System.IO.BufferedStream.ReadByteSlow() at System.IO.BufferedStream.ReadByte() at CSRedis.Internal.IO.RedisReader.ReadType() at CSRedis.Internal.IO.RedisReader.ExpectType(RedisMessage expectedType) at CSRedis.Internal.IO.RedisReader.ReadStatus(Boolean checkType) at CSRedis.Internal.Commands.RedisStatus.Parse(RedisReader reader) at CSRedis.Internal.RedisConnector.Call[T](RedisCommand
1 command)
at CSRedis.RedisClient.Write[T](RedisCommand1 command)
能不能实现ZRangeByScor把Score的值也一同返回,用来统计7日、30日访问量等需要用到
数据如下(例):
ArticleViewCount:20180930
文章编号 访问量
1 20
2 192
目前测了一下用CSRedisClient订阅之后,模拟断一下网然后恢复(禁用网卡),重新连上之后,就无法收到原先订阅的Channel了。
而且发现网络断一下之后,所有的API调用都会巨卡,感觉是每个命令都达到了超时时间。版本是2.6.9。
csreids 错误【192.168.1.19:7000/0】:发送数据长度 10259 大于 异步写入缓冲块大小 10240,请设置连接串参数:writeBuffer at CSRedis.CSRedisClient.GetAndExecuteAsync[T](RedisClientPool pool, Func`2 handerAsync, Int32 jump)
大佬有没有文档或者教程啊
集群配置不支持?怎么处理?
连接池中链接一旦创建之后在一定时间不用之后会销毁链接码?
在线上项目中发现以下问题:
ERR max number of clients reached
重启以下服务就可以了。
然后观察redis的连接数。在服务运行期间connected_clients一直在不断的增加。
` var csredis = new CSRedis.CSRedisClient("ip,password=xxxx");
RedisHelper.Initialization(csredis,
value => Newtonsoft.Json.JsonConvert.SerializeObject(value),
deserialize: (data, type) => Newtonsoft.Json.JsonConvert.DeserializeObject(data, type));
RedisHelper.Set("test1", "123123");`
错误日志如下:
System.Net.Sockets.SocketException (23): Too many open files in system
at CSRedis.CSRedisClient.GetConnectionAndExecute[T](ConnectionPool pool, Func2 handle) at CSRedis.CSRedisClient.ExecuteScalar[T](String key, Func
3 hander)
at CSRedis.CSRedisClient.Get(String key)
at RedisHelper.Get(String key)
使用分布式缓存时提示与最新版本有冲突,netcore 2.1.0 rc1
为什么要这么设定呢?
我在测试CSRedis跟StackExchange.Redis的时候,还是有一些不同点, 想看下CSRedis Benchmark的测试代码.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.