csredis

本文涉及的产品
云数据库 Tair(兼容Redis),内存型 2GB
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
简介:

CSRedis is a .NET client for Redis and Redis Sentinel (2.8.12). Includes both synchronous and asynchronous implementations.

The easiest way to install CSRedis is from NuGet via the Package Manager Console:

PM> Install-Package csredis

Basic usage

Whenever possible, server responses are mapped to the appropriate CLR type.

using (var redis = new RedisClient("yourhost"))
{
    string ping = redis.Ping();
    string echo = redis.Echo("hello world");
    DateTime time = redis.Time();
}

Asynchronous commands are also available.

using (var redis = new RedisClient("localhost"))
{
    // fire-and-forget: results are not captured
    for (int i = 0; i < 5000; i++)
    {
        redis.IncrAsync("test1");
    }

    // callback via ContinueWith: Ping is executed asyncronously, and when a result is ready, the response is printed to screen.
    redis.TimeAsync().ContinueWith(t => Console.WriteLine(t.Result));

    // blocking call
    string result = redis.GetAsync("test1").Result;
}

Use the IRedisClient or IRedisClientAsync interfaces to use synconous or asyncronous methods exclusively.

using (IRedisClient csredis = new RedisClient(Host))
{
    // only syncronous methods exposed
}

using (IRedisClientAsync csredis = new RedisClient(Host))
{
    // only asyncronous methods exposed
}

Pipelining

CSRedis supports pipelining commands to lessen the effects of network overhead on sequential server calls. To enable pipelining, wrap a group of commands between StartPipe() and EndPipe(). Note that redis-server currently has a 1GB limit on client buffers but CSRedis does not enforce this. Similar performance gains may be obtained by using the deferred Task/Asyncronous methods.

using (var redis = new RedisClient("localhost"))
{
    redis.StartPipe();
    var empty1 = redis.Echo("hello"); // returns immediately with default(string)
    var empty2 = redis.Time(); // returns immediately with default(DateTime)
    object[] result = redis.EndPipe(); // all commands sent to the server at once
    var item1 = (string)result[0]; // cast result objects to appropriate types
    var item2 = (DateTime)result[1];

    // automatic MULTI/EXEC pipeline: start a pipe that is also a MULTI/EXEC transaction
    redis.StartPipeTransaction();
    redis.Set("key", "value");
    redis.Set("key2", "value2");
    object[] result2 = redis.EndPipe(); // transaction is EXEC'd automatically if DISCARD was not called first
    
    // DISCARD pipelined transaction
    redis.StartPipeTransaction();
    redis.Set("key", 123);
    redis.Set("key2", "abc");
    redis.Discard();
}

Why csredis?

There are a handful of .NET redis clients in active development, but none quite suited my needs: clean interface of the native Redis API; Sentinel support; easy-to-use pipelining/async. If there are gaps between CSRedis and another implementation please open an Issue or Pull Request.

Authentication

Password authentication is handled according to the native API (i.e. not in the connection constructor):

redis.Auth("mystrongpasword");

Reconnecting

CSRedis supports a simple reconnect option to handle dropped connections to the same Redis host. See RedisSentinelManager for a fuller implementation between multiple masters.

using (var redis = new RedisClient("localhost"))
{
    redis.Connected += (s, e) => redis.Auth(Password); // set AUTH, CLIENT NAME, etc
    redis.ReconnectAttempts = 3;
    redis.ReconnectWait = 200;
    // connection will retry 3 times with 200ms in between before throwing an Exception
}

Flexible hash mapping

Pass any POCO or anonymous object to the generic hash methods:

redis.HMSet("myhash", new
{
  Field1 = "string",
  Field2 = true,
  Field3 = DateTime.Now,
});

MyPOCO hash = redis.HGetAll<MyPOCO>("my-hash-key");
AI 代码解读

Or use a string Dictionary:

redis.HMSet("mydict", new Dictionary<string, string>
{
  { "F1", "string" },
  { "F2", "true" },
  { "F3", DateTime.Now.ToString() },
});

Dictionary<string, string> mydict = redis.HGetAll("my-hash-key");
AI 代码解读

Or use the native API:

redis.HMSet("myhash", new[] { "F1", "string", "F2", "true", "F3", DateTime.Now.ToString() });

Transactions

Synchronous transactions are handled using the API calls MULTI/EXEC/DISCARD. Attach an event handler to RedisClient.TransactionQueued event to observe server queue replies (typically 'OK'). When inside of a transaction, command return values will be default(T).

redis.TransactionQueued += (s, e) =>
{
    Console.WriteLine("Transaction queued: {0}({1}) = {2}", e.Command, String.Join(", ", e.Arguments), e.Status);
};
redis.Multi();
var empty1 = redis.Set("test1", "hello"); // returns default(String)
var empty2 = redis.Set("test2", "world"); // returns default(String)
var empty3 = redis.Time(); // returns default(DateTime)
object[] result = redis.Exec();
var item1 = (string)result[0];
var item2 = (string)result[1];
var item3 = (DateTime)result[2];

Subscription model

The subscription model is event based. Attach a handler to one or both of SubscriptionChanged/SubscriptionReceived to receive callbacks on subscription events. Opening the first subscription channel blocks the main thread, so unsubscription (and new subscriptions) must be handled by a background thread/task.

SubscriptionChanged: Occurs when a subsciption channel is opened or closed
RedisSubscriptionReceived: Occurs when a subscription message has been received

Example:

redis.SubscriptionChanged += (s, e) =>
{
  Console.WriteLine("There are now {0} open channels", e.Response.Count);
};
redis.SubscriptionReceived += (s, e) =>
{
  Console.WriteLine("Message received: {0}", e.Message.Body);
};
redis.PSubscribe("*");

Future-proof

CSRedis exposes a basic Call() method that sends arbitrary commands to the Redis server. Use this command to easily implement future Redis commands before they are included in CSRedis. This can also be used to work with "bare-metal" server responses or if a command has been renamed in redis.conf.

object resp = redis.Call("ANYTHING", "arg1", "arg2", "arg3");

Note that the response object will need to be cast according to the Redis unified protocol: status (System.String), integer (System.Int64), bulk (System.String), multi-bulk (System.Object[]).

Streaming responses

For large result sizes, it may be preferred to stream the raw bytes from the server rather than allocating large chunks of memory in place. This can be achieved with RedisClient.StreamTo(). Note that this only applies to BULK responses (e.g. GET, HGET, LINDEX, etc). Attempting to stream any other response will result in an InvalidOperationException. Here is an example that stores the response in a MemoryStream 64 bytes at a time. A more useful example might use a FileStream and a larger buffer size.

redis.Set("test", new string('x', 1048576)); // 1MB string
using (var ms = new MemoryStream())
{
    redis.StreamTo(ms, 64, r => r.Get("test")); // read in small 64 byte blocks
    byte[] bytes = ms.ToArray(); // optional: get the bytes if needed
}

Tracing

Use .NET tracing to expose low level TCP messages

Sentinel

RedisSentinelManager is a managed connection that will automatically obtain a connection to a Redis master node based on information from one or more Redis Sentinel nodes. Async methods coming soon

using (var sentinel = new RedisSentinelManager("host1:123", "host2:456"))
{
    sentinel.Add(Host); // add host using default port 
    sentinel.Add(Host, 36379); // add host using specific port
    sentinel.Connected += (s, e) => sentinel.Call(x => x.Auth(Password)); // this will be called each time a master connects
    sentinel.Connect("mymaster"); // open connection
    var test2 = sentinel.Call(x => x.Time()); // use the Call() lambda to access the current master connection
}





本文作者:陈群
本文来自云栖社区合作伙伴rediscn,了解相关信息可以关注redis.cn网站。
相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
目录
打赏
0
0
0
0
26197
分享
相关文章
快速解决idea启动项目报错:Unable to open debugger port(127.0.0.1:58950):java.net.SocketException“socket closed
快速解决idea启动项目报错:Unable to open debugger port(127.0.0.1:58950):java.net.SocketException“socket closed
1318 0
TDSQL技术详解
一个基本的TDSQL实例的创建和操作流程。对于更高级的特性和最佳实践
746 0
TDSQL技术详解
小鱼深度评测 | 通义灵码2.0,不仅可跨语言编码,自动生成单元测试,更炸裂的是集成DeepSeek模型且免费使用,太炸裂了。
小鱼深度评测 | 通义灵码2.0,不仅可跨语言编码,自动生成单元测试,更炸裂的是集成DeepSeek模型且免费使用,太炸裂了。
141061 20
小鱼深度评测 | 通义灵码2.0,不仅可跨语言编码,自动生成单元测试,更炸裂的是集成DeepSeek模型且免费使用,太炸裂了。
基于阿里百炼的DeepSeek-R1满血版模型调用【零门槛保姆级2084小游戏开发实战】
本文介绍基于阿里百炼的DeepSeek-R1满血版模型调用,提供零门槛保姆级2048小游戏开发实战。文章分为三部分:定位与核心优势、实战部署操作指南、辅助实战开发。通过详细步骤和案例展示,帮助开发者高效利用DeepSeek-R1的强大推理能力,优化游戏逻辑与视觉效果,解决官网响应延迟问题,提升开发效率和用户体验。适合企业开发者、教育行业及多模态探索者使用。
70897 17
基于阿里百炼的DeepSeek-R1满血版模型调用【零门槛保姆级2084小游戏开发实战】
深度评测 | 仅用3分钟,百炼调用满血版 Deepseek-r1 API,百万Token免费用,简直不要太爽。
仅用3分钟,百炼调用满血版Deepseek-r1 API,享受百万免费Token。阿里云提供零门槛、快速部署的解决方案,支持云控制台和Cloud Shell两种方式,操作简便。Deepseek-r1满血版在推理能力上表现出色,尤其擅长数学、代码和自然语言处理任务,使用过程中无卡顿,体验丝滑。结合Chatbox工具,用户可轻松掌控模型,提升工作效率。阿里云大模型服务平台百炼不仅速度快,还确保数据安全,值得信赖。
358011 62
深度评测 | 仅用3分钟,百炼调用满血版 Deepseek-r1 API,百万Token免费用,简直不要太爽。
快速使用 DeepSeek-R1 满血版
DeepSeek是一款基于Transformer架构的先进大语言模型,以其强大的自然语言处理能力和高效的推理速度著称。近年来,DeepSeek不断迭代,从DeepSeek-V2到参数达6710亿的DeepSeek-V3,再到性能比肩GPT-4的DeepSeek-R1,每次都带来重大技术突破。其开源策略降低了AI应用门槛,推动了AI普惠化。通过阿里云百炼调用满血版API,用户可以快速部署DeepSeek,享受高效、低成本的云端服务,最快10分钟完成部署,且提供免费token,极大简化了开发流程。
191015 23
快速使用 DeepSeek-R1 满血版
Manus:或将成为AI Agent领域的标杆
随着人工智能技术的飞速发展,AI Agent(智能体)作为人工智能领域的重要分支,正逐渐从概念走向现实,并在各行各业展现出巨大的应用潜力。在众多AI Agent产品中,Manus以其独特的技术优势和市场表现,有望成为该领域的标杆。作为资深AI工程师,本文将深入探讨Manus的背景知识、主要业务场景、底层原理、功能的优缺点,并尝试使用Java搭建一个属于自己的Manus助手,以期为AI Agent技术的发展和应用提供参考。
11071 13
阿里云百炼已上线超强推理开源模型QwQ-32B,尺寸更小,性能比肩DeepSeek满血版
通义千问团队推出了320亿参数的QwQ-32B模型,通过大规模强化学习和多阶段训练,在数学、编程及通用能力上达到或超越了DeepSeek-R1等先进模型。QwQ-32B模型已在阿里云百炼上线,支持API调用,用户可通过官方文档了解详细使用方法。未来,团队将继续探索智能体与RL集成,推动人工通用智能的发展。
快来零门槛、即刻拥有 DeepSeek-R1 满血版
随着人工智能技术的发展,DeepSeek作为一款新兴推理模型,凭借强大的技术实力和广泛的应用场景崭露头角。本文基于阿里云提供的零门槛解决方案,评测DeepSeek的部署与使用。该方案支持多模态任务,涵盖文本生成、代码补全等,融合NLP、IR和ML技术,提供快速实现AI应用的便利。用户无需编码,最快5分钟、最低0元即可部署DeepSeek模型。阿里云还提供100万免费Token,适合预算有限的个人或小型团队试用。通过Chatbox客户端配置API,用户可轻松体验智能交互功能,如数学提问和代码书写等。
37604 5