In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article will explain in detail how to use StackExchange.Redis in C#. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.
Install StackExchange.Redis
Search for StackExchange.Redis and Newtonsoft.Json in NuGet and click the button to install it.
StackExchange.Redis is the client for C # to operate the Redis database.
Newtonsoft.Json is used to serialize Josn strings and deserialize to get objects.
Citation and initialization
Quote
Using StackExchange.Redis;using Newtonsoft.Json
Initialize redis
ConnectionMultiplexer _ conn = RedisConnectionHelp.Instance;// initialization var database = _ conn.GetDatabase (0); / / specify the connected library 0String (string)
String is the most commonly used data type, and ordinary key/value storage can be classified as such.
A Key corresponds to a Value,string type that is binary safe. Redis's string can contain any data, such as jpg images (generating binaries) or serialized objects.
Database.StringSet ("name", "Cang"); / / set StringSet (key, value) string str = database.StringGet ("name"); / / result: grey database.StringSet ("name_two", str, TimeSpan.FromSeconds (10)); / / set time, expire after 10 seconds.
Save the object (the object needs to be serialized into a string and then stored in the library)
Fetch object (deserialization)
/ / create object Demo demo = new Demo () {Name = "Cang", Age = 18, Height = 1.83}; string demojson = JsonConvert.SerializeObject (demo); / / serialize database.StringSet ("model", demojson); string model = database.StringGet ("model"); demo = JsonConvert.DeserializeObject (model); / / deserialize
StringIncrement increment, StringDecrement decrement (default is both 1)
Double increment = 0double decrement = 0bot for (int I = 0; I)
< 3; i++){ increment = database.StringIncrement("StringIncrement", 2);//增量,每次+2}for (int i = 0; i < 3; i++){ decrement = database.StringDecrement("StringIncrement");//减量,每次-1}List(列表) Redis 列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部或者尾部。 一个列表最多可以包含 232 - 1 个元素 (4294967295, 每个列表超过 40 亿个元素)。 for (int i = 0; i < 10; i++){ database.ListRightPush("list", i);//从底部插入数据}for (int i = 10; i < 20; i++){ database.ListLeftPush("list", i);//从顶部插入数据}var length = database.ListLength("list");//长度 20var rightPop = database.ListRightPop("list");//从底部拿出数据var leftpop = database.ListLeftPop("list");//从顶部拿出数据var list = database.ListRange("list"); Hash(哈希) Redis hash 是一个 string 类型的 field 和 value 的映射表,hash 特别适合用于存储对象。相对于将对象的每个字段存成单个 string类型。一个对象存储在 hash 类型中会占用更少的内存,并且可以更方便的存取整个对象。 Redis 中每个 hash 可以存储 232- 1 键值对(40多亿)。 Hash 的存储,给我的感觉类似于关系型数据库。以下面的例子为例,存储一个 user 对象(关系型数据库里的表名), cang、shan、yun (关系型数据库里的数据的主键、唯一值),json(字段) string json = JsonConvert.SerializeObject(demo);//序列化database.HashSet("user", "cang", json);database.HashSet("user", "shan", json);database.HashSet("user", "yun", json);//获取Modelstring hashcang = database.HashGet("user", "cang");demo = JsonConvert.DeserializeObject(hashcang);//反序列化//获取ListRedisValue[] values = database.HashValues("user");//获取所有valueIList demolist = new List();foreach (var item in values){ Demo hashmodel = JsonConvert.DeserializeObject(item); demolist.Add(hashmodel);}发布订阅 Redis 发布订阅 (pub/sub) 是一种消息通信模式,可以用于消息的传输,Redis 的发布订阅机制包括三个部分,发布者,订阅者和 Channel。适宜做在线聊天、消息推送等。 发布者和订阅者都是 Redis 客户端,Channel 则为 Redis 服务器端,发布者将消息发送到某个的频道,订阅了这个频道的订阅者就能接收到这条消息,客户端可以订阅任意数量的频道。 ISubscriber sub = _conn.GetSubscriber();//订阅 Channel1 频道sub.Subscribe("Channel1", new Action((channel, message) =>{Console.WriteLine ("Channel1" + "subscription received message:" + message);}); for (int I = 0; I
< 10; i++){ sub.Publish("Channel1", "msg" + i);//向频道 Channel1 发送信息 if (i == 2) { sub.Unsubscribe("Channel1");//取消订阅 }} 因为当 i == 2 的时候取消订阅,所以收到的订阅消息只有3条。Business
After the transaction is opened, the corresponding command operation is encapsulated as a request to Redis for execution when the Execute method is called.
Here you create a thing through the CreateTransaction function (multi) and call its Execute function (exec) to submit the thing.
The "Condition.StringEqual (" name ", name)" is equivalent to the watch name in the Redis command.
String name = database.StringGet ("name"); string age = database.StringGet ("age"); var tran = database.CreateTransaction (); / create thing tran.AddCondition (Condition.StringEqual ("name", name)); / / optimistic lock tran.StringSetAsync ("name", "sea"); tran.StringSetAsync ("age", 25); database.StringSet ("name", "Cang"); / change name value at this time, the submission of things will fail. Bool committed = tran.Execute (); / / submit the transaction, true is successful, false rollback.
Because the name value was modified during the submission process, resulting in a rollback, all name assignment and age assignment 25 failed.
Batch batch operation
Batch packages the commands that need to be executed as a request to Redis, and then waits for the result to be returned. Reduce network overhead.
Var batch = database.CreateBatch (); / / bulk write Task T1 = batch.StringSetAsync ("name", "Yu"); Task T2 = batch.StringSetAsync ("age", 22); batch.Execute (); Task.WaitAll (T1, T2); Console.WriteLine ("Age:" + database.StringGet ("age")); Console.WriteLine ("Name:" + database.StringGet ("name")); / / batch write for (int I = 0; I < 100000) Batch.Execute +) {batch.StringSetAsync ("age" + I, I);} batch.Execute (); / batch read List valueList = new List (); for (int I = 0; I < 10000; iBo +) {Task tres = batch.StringGetAsync ("age" + I); valueList.Add (tres);} batch.Execute (); foreach (var redisValue in valueList) {string value = redisValue.Result;// fetch the corresponding value} Lock (distributed lock)
Because Redis is a single-threaded model and command operations are atomic, it is easy to use this feature to implement distributed locks.
RedisValue token = Environment.MachineName;//lock_key represents the name of the lock in the redis database and cannot be repeated. / / token is used to identify who owns the lock and to release the lock. / / TimeSpan indicates the validity time of the lock. Automatically released after 10 seconds to avoid deadlock. If (database.LockTake ("lock_key", token, TimeSpan.FromSeconds (10)) {try {/ / TODO: start doing what you need Thread.Sleep (5000);} finally {database.LockRelease ("lock_key", token); / / release lock}} StackExchange.Redis encapsulation
Inside is the package and test code.
Link: https://pan.baidu.com/s/1rT9z567MVtfzQtnvdUxffw password: 5k1b
Environment: vs2013 + .NET framework 4.5
Related articles:
Download and install Redis Windows version
Redis Visualization tool Redis Desktop Manager
Redis Master / Slave configuration (Windows version)
This is the end of the article on "how to use StackExchange.Redis in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.