Install CSRedis
Search and install directly using the Nuget package manager in Visual Studio
Before starting
Create a redis instance using the connection string and execute redishelper Initialization().
var csredis = new CSRedisClient("127.0.0.1:6379,password=YourPassword"); RedisHelper.Initialization(csredis);
If you don't set a password for redis, just write the ip directly. Otherwise, write the password into the connection string.
var csredis = new CSRedisClient("127.0.0.1:6379"); RedisHelper.Initialization(csredis);
Then you can redis.
String (string)
About value of string:
- value can be used to store data in any format, such as json, jpg and even video files;
- The maximum capacity of value is 512M;
- value can store three types of values: byte string, integer (int) and floating point number (double);
The integer value range is the same as the long integer value range of the system. On the 32-bit operating system, the integer is 32 bits; On a 64 bit operating system, an integer is a 64 bit signed integer. The value range of floating-point number is the same as that of double precision floating-point number in IEEE 754 standard.
Simple operation using CSRedis
// Add string key value pair csredis.Set("hello", "1"); csredis.Set("world", "2"); csredis.Set("hello", "3"); // Get the corresponding value according to the key csredis.Get("hello"); // Removing Elements csredis.Del("world");
When the same key is assigned multiple times, the value of the key is the value at the last assignment, and the value corresponding to hello in the instance is finally 3.
Because redis can "identify" the type of string, we can not only add, delete, query and delete the string, but also add and subtract the integer type, and read or write part of the byte string.
/* Numerical operation */ csredis.Set("num-key", "24"); // value += 5 csredis.IncrBy("num-key",5); // output -> 29 // value -= 10 csredis.IncrBy("num-key", -10); // output -> 19
/* Byte string operation */ csredis.Set("string-key", "hello "); // Append a string to the end of the value of the specified key csredis.Append("string-key", "world"); // output -> "hello world" // Gets the substring composed of all characters from the specified range (start:3,end:7) csredis.GetRange("string-key",3,7) // output -> "lo wo" // Overwrites the original value (index:4) from the specified position with a new string csredis.SetRange("string-key", 4, "aa"); // output -> "hellaaword"
Abnormal conditions
- redis will report an error when the byte string is self incremented or self decremented.
- When using the Append and SetRange methods to write value, the length of the byte string may not be enough. At this time, redis will use the null character to expand the value to the specified length, and then write.
List
- The list can orderly store multiple strings (strings can be repeated) and other operations;
- The list is implemented through a linked list, so it adds new elements very quickly.
// Push the element from the right end csredis.RPush("my-list", "item1", "item2", "item3", "item4"); // Pop element from right csredis.RPop("my-list"); // Push element from left csredis.LPush("my-list","LeftPushItem"); // Pop element from left csredis.LPop("my-list"); // Traverse the linked list elements (start:0,end:-1 to return all elements) foreach (var item in csredis.LRange("my-list", 0, -1)) { Console.WriteLine(item); } // Get the element by the index value (when the index value is greater than the length of the linked list, a null value will be returned and no error will be reported) Console.WriteLine($"{csredis.LIndex("my-list", 1)}"); // Trim elements within the specified range (start:4,end:10) csredis.LTrim("my-list", 4, 10);
In addition to the above simple processing of the elements in the list, you can also copy the elements in one list to another list. Semantically, the left end of the list is "head" by default, and the right end of the list is "tail".
// Pop up the last element of my list and press it into the head of another list csredis.RPopLPush("my-list", "another-list");
Set
The collection stores different elements in an unordered manner, that is, the Key of each element in the collection is not repeated. In redis, you can quickly add and remove collections.
// In fact, only two elements ("item1","item2") are inserted csredis.SAdd("my-set", "item1", "item1", "item2"); // Traversal of sets foreach (var member in csredis.SMembers("my-set")) { Console.WriteLine($"Collection members:{member.ToString()}"); } // Determine whether the element exists string member = "item1"; Console.WriteLine($"{member}Does it exist:{csredis.SIsMember("my-set", member)}"); // output -> True // Removing Elements csredis.SRem("my-set", member); Console.WriteLine($"{member}Does it exist:{csredis.SIsMember("my-set", member)}"); // output -> False // Remove an element at random csredis.SPop("my-set");
The above operations are performed on the elements in a set. In addition, you can also perform intersection, union and difference operations on two sets
csredis.SAdd("set-a", "item1", "item2", "item3","item4","item5"); csredis.SAdd("set-b", "item2", "item5", "item6", "item7"); // Difference set csredis.SDiff("set-a", "set-b"); // output -> "item1", "item3","item4" // intersection csredis.SInter("set-a", "set-b"); // output -> "item2","item5" // Union csredis.SUnion("set-a", "set-b"); // output -> "item1","item2","item3","item4","item5","item6","item7"
In addition, sdiffstore, sinterstore and sunionstore can be used to store the results of the operation in a new collection.
Hash (hashmap)
In redis, we can use hash to store multiple key value pairs on one redis key, so as to store a series of related data together. For example, add a redis key Article:1001, and then store the title, author, link, likes and other information of the article with ID 1001 in this key. We can think of such a dataset as rows in a relational database.
// Add element to hash csredis.HSet("ArticleID:10001", "Title", "stay.NET Core Used in CSRedis"); csredis.HSet("ArticleID:10001", "Author", "xscape"); csredis.HSet("ArticleID:10001", "PublishTime", "2019-01-01"); csredis.HSet("ArticleID:10001", "Link","https://www.cnblogs.com/xscape/p/10208638.html"); // Get the elements in the hash according to the Key csredis.HGet("ArticleID:10001", "Title"); // Gets all elements in the hash foreach (var item in csredis.HGetAll("ArticleID:10001")) { Console.WriteLine(item.Value); }
HGet and HSet methods can only process one key value pair at a time, while HMGet and HMSet are their multi parameter versions, which can process multiple key value pairs at a time.
var keys = new string[] { "Title","Author","publishTime"}; csredis.HMGet("ID:10001", keys);
Although all values can be retrieved by using HGetAll, sometimes the values contained in the hash may be very large, which is easy to cause server congestion. To avoid this situation, we can use HKeys to retrieve all keys of the hash (HVals can retrieve all values), and then use HGet method to retrieve the values corresponding to the keys one by one.
foreach (var item in csredis.HKeys("ID:10001")) { Console.WriteLine($"{item} - {csredis.HGet("ID:10001", item)}"); }
Like processing strings, we can also increase and decrease the values in the hash. The principle is the same as that of strings.
csredis.HSet("ArticleID:10001", "votes", "257"); csredis.HIncrBy("ID:10001", "votes", 40); // output -> 297
Ordered set
The ordered set can be regarded as a sortable hash, but the val of the ordered set becomes the score score. The elements in the set are sorted based on the score, which is stored in the format of double precision floating-point number.
// Add elements to an ordered collection csredis.ZAdd("Quiz", (79, "Math")); csredis.ZAdd("Quiz", (98, "English")); csredis.ZAdd("Quiz", (87, "Algorithm")); csredis.ZAdd("Quiz", (84, "Database")); csredis.ZAdd("Quiz", (59, "Operation System")); //Returns the number of elements in the collection csredis.ZCard("Quiz"); // Gets the collection of elements in the specified range (90 ~ 100) in the collection csredis.ZRangeByScore("Quiz",90,100); // Gets all elements of the collection and sorts them in ascending order csredis.ZRangeWithScores("Quiz", 0, -1); // Remove elements from collection csredis.ZRem("Quiz", "Math");
affair
atomic transaction
Transaction can ensure that when a client executes multiple commands, it will not be interrupted by other clients, which is different from the transaction of relational database. The transaction requires MULTI and EXEC commands. Redis will execute the code surrounded by MULTI and EXEC in turn. After the transaction is completed, redis will process the commands of other clients.
Pipeline
Redis transactions are implemented through pipeline. When using pipeline, the client will automatically call MULTI and EXEX commands, package multiple commands and send them to redis at one time, and then redis will package all the execution results of the commands and return them to the client at one time. This effectively reduces the number of communication between redis and the client and improves the performance when executing multiple commands.
var pipe = csredis.StartPipe(); for (int i = 0; i < COUNT; i++) { pipe.IncrBy("key-one"); // The value in key one is incremented by COUNT times to generate COUNT IncrBy commands } pipe.EndPipe(); // At the end of the pipeline, COUNT commands are sent to redis at one time Console.WriteLine($"{csredis.Get("key-one")}"); Console.ReadKey();
Expiration of Key
redis also allows us to set the validity period for the key. When the key expires, the key does not exist.
redis.Set("MyKey", "hello,world"); Console.WriteLine(redis.Get("MyKey")); // output -> "hello,world" redis.Expire("MyKey", 5); // The key expires after 5 seconds. You can also use the expierat method to make it expire automatically at the specified time Thread.Sleep(6000); // Pause for 6 seconds Console.WriteLine(redis.Get("MyKey")); // output -> ""