csredis base usage
Basic usage
Whenever possible, server responses are mapped to the appropriate CLR type. using (var redis = new RedisClient("yourhost"))//只需输入redis 服务器的ip 端口默认为 6379
{
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 = ; i < ; 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[]; // cast result objects to appropriate types
var item2 = (DateTime)result[]; // 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", );
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 = ;
redis.ReconnectWait = ;
// 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,
});
//批量取值
string[] a = new string[] { "Field1", "Field2", "Field3" };
redis.HMGet("myhash", a);
// 强类型映射
MyPOCO hash = redis.HGetAll<MyPOCO>("my-hash-key");
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");
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[];
var item2 = (string)result[];
var item3 = (DateTime)result[];
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 bytes at a time. A more useful example might use a FileStream and a larger buffer size. redis.Set("test", new string('x', )); // 1MB string
using (var ms = new MemoryStream())
{
redis.StreamTo(ms, , 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, ); // 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
}
© GitHub, Inc.
csredis base usage的更多相关文章
- StickyListHeaders的使用
我们知道在ios中字母的导航有悬停的效果,在android中,git上有大神实现了这种悬停的功能,我们只要将普通的Listview改为StickyListHeadersListView然后设置adap ...
- C++11智能指针 share_ptr,unique_ptr,weak_ptr用法
0x01 智能指针简介 所谓智能指针(smart pointer)就是智能/自动化的管理指针所指向的动态资源的释放.它是存储指向动态分配(堆)对象指针的类,用于生存期控制,能够确保自动正确的销毁动 ...
- Python 处理脚本的命令行参数(三):使用argparse
# coding:utf-8 # 测试argparse模块的基本用法 import argparse # 创建参数解析对象,并添加脚本用法帮助 parser = argparse.ArgumentPa ...
- $python打包工具pyinstaller的用法
pyinstaller是一个很好用的python打包工具,在Windows环境下可以将python脚本打包成一个exe可执行文件,并且脚本中所依赖的各种第三方库在打包时候都会被统一处理到一起,这样打包 ...
- $命令行参数解析模块argparse的用法
argparse是python内置的命令行参数解析模块,可以用来为程序配置功能丰富的命令行参数,方便使用,本文总结一下其基本用法. 测试脚本 把以下脚本存在argtest.py文件中: # codin ...
- Python3常用模块的安装
1.mysql驱动:mysql-connector-python 1.安装 $ pip3 install mysql-connector-python --allow-external mysql-c ...
- C++11 新特性之智能指针(shared_ptr, unique_ptr, weak_ptr)
这是C++11新特性介绍的第五部分,涉及到智能指针的相关内容(shared_ptr, unique_ptr, weak_ptr). shared_ptr shared_ptr 基本用法 shared_ ...
- maven install
1. install maven under ubuntu apt install maven 2 speed up package download vim ~/.m2/settings.xml & ...
- [转]Dynamic SQL & Stored Procedure Usage in T-SQL
转自:http://www.sqlusa.com/bestpractices/training/scripts/dynamicsql/ Dynamic SQL & Stored Procedu ...
随机推荐
- CRM 2016 请求"System.Security.Permissions.FilelOPermission,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken=b77a5c561934e089"类型的权限已失败.
CRM 请求"System.Security.Permissions.FilelOPermission,mscorlib,Version=4.0.0.0,Culture=neutral,Pu ...
- Linux下用node-inspector实现NodeJS远程调试开发
1.首先安装 node-inspector npm install -g node-inspector -g表示全局安装,如果像我一样安装失败,再试几次,npm偶尔就会这样抽风... 这一步是关键的, ...
- 微信小程序支付签名老是失败,在官网的校验签名工具校验成功,老是返回签名失败
在网上也百度了各种签名不正确的解决方法,都没有问题,但签名就是不成功,实在找不出问题了,我就重置了一下api秘钥,结果成功了…… 不知道什么原因第一次填写的api秘钥也是我重置的,填写的也没有问题,但 ...
- elastalert新增自定义警告推送
举例,博主公司有自己的内部通讯工具(类似QQ),接下来用IM代称该工具.于是希望elastalert的警告推送可以支持IM的公众号群发功能. 等博主这个月知识库写了再来补充hah
- web api 本地测试
[最简单的,本人小白,大神勿喷] 一:创建web API 服务端 ①创建web api 的项目 ②在这个api项目的Web.config中加上如下几段话: <httpProtocol>&l ...
- Ubuntu安装MyEclise16 过程差不多
选择好安装路径,和workpace路径,可能会因为工作空间放的位置不太对,导致myeclipse出现问题. 1.Ubuntu安装MyEclise10 不知道为什么网上会有那么多安装过程,还有配置目录和 ...
- 从入门到熟悉 HTTPS 的 9 个问题
九个问题从入门到熟悉HTTPS 最近一边做毕设一边学习编程.前两天她问我 HTTPS 的问题,本来想直接扔一篇网上的教程给她.后来想了一下,那些文章大多直接介绍概念, 对新手不太友好,于是我干脆亲自给 ...
- 20165205 学习基础与C语言基础调查
学习基础和C语言基础调查 从<做中学>学到的经验 首先,在老师的这几篇文章中,最核心的一片文章就是<做中学>这一篇了,在文章中强调了不断联系的重要性,然后在学以致用的过程中发现 ...
- django交互vue遇到的问题
接受列表(数组): request.POST.get('array', '') # 结果得到数组的最后一个元素 request.POST.getlist('array', '') # 获取整个列表
- [UGUI]滑动列表优化(循环利用)
需要注意的有下面几点: 1. 区分好表现上的index和逻辑上的index.表现上的index是指这个go是go列表中的第几项,但实际上这个index的意义并不大,因为在滚动的过程中go列表是轮转的: ...