Summary
The previous article described the installation of the Redis client and server side, as well as a general introduction to Redis. This article focuses on explaining. NET4.0 and. How to manipulate a hash table using Redis and C # Redis in NET4.5. And some code from the package will be pasted. In the course of the explanation, I intend to combine the Redis operation command with the description, as a comparison. This also gives the reader a clear idea of which of the Redis commands the coded code corresponds to.
Introduction to hash hash table
Here is just a simple concept-level introduction to the hash table (from CSDN), if necessary, to study it yourself.
1, the concept of a hash table
A hash table (hash table) is also known as a hash table, which is a data structure that is accessed directly based on key value. It accesses records by mapping key code values to a location in the hash table to speed up lookups . This mapping function does a hash function, and the array that holds the record is called the hash table.
2. Time complexity of hash table lookup
The hash table stores the key-value pairs, and the time complexity of the lookup is irrelevant to the number of elements, and the hash table locates the elements by calculating the hash code value to locate the element's position and thus directly accessing the element, so the time complexity of the hash table lookup is O (1).
How to be in. Install Redis components in net4.0/4.5?
In the previous blog post, install the Redis server side and remember to turn on the service. And then in. Add a reference to the DLL file for the Redis operation in the NET4.5 (. NET4.0) project. The steps to refer to are as follows:
First step: Right-click the reference in the project and select "Manage NuGet packages";
Step Two: Enter "Redis Client for the Redis NoSQL DB" in the search field and find it online;
The first component in the online search structure, such as the Red region, whose version number is 4.0.35, is the component to be installed. Next we continue to click on the "Install" button, enter the download component, and so on after the download is complete, continue to select "Accept the terms", and then continue to install. The situation occurs during installation:
This red error means that we have installed the Servicestack.interfaces 4.0.35 version with the current. The components in the NET4.5 framework are incompatible. This shows that we need to reduce or improve. NET version to resolve this issue. I installed the. NET4.5, so I can only lower the version. Reduce. NET version of the method you should all know. I was in the wearies once, I hope you don't want to, after all, there are beginners in. Method: Right-click the project file Select "Properties" = "application" = = "Target Framework" and select each version to try the previous two steps until it can be installed.
I tried. NET4.0 will also encounter the same problem until. NET3.5 can. Of course the Servicestack.interfaces version installed at this time is 1.0.0.0, so we'll put. NET version Recovery 4.5 is ready for use. , in fact, is disguised in. Use Redis client under net4.0/4.5. Do not know whether you encounter such a problem, or directly copy other people's DLL files. When you personally go to the operation, you will find that, in fact, the installation of a component can cause a variety of problems. So, if we want to understand the whole process, we still have to practise it. Okay, so that means in. The Redis client has been installed under NET4.5.
Actual combat: Using Redis code in the project
This section mainly explains how to connect to a Redis server. With a lot of configuration, I'll use the code to explain everything. The following code is in the configuration file:
1 <configSections>
2 <section name="RedisConfig" type="RedisDemo.Common.Redis.RedisConfigInfo, RedisDemo"/>
3 </configSections>
4 <RedisConfig WriteServerList="127.0.0.1:6379" ReadServerList="127.0.0.1:6379" MaxWritePoolSize="60"
MaxReadPoolSize="60" AutoStart="true" LocalCacheTime="180" RecordeLog="false"/>
Here is a description of the properties of this section of the Redisconfig configuration file.
writeserverlist: A writable Redis link address.
readserverlist: A readable redis link address.
maxwritepoolsize: Maximum number of write links.
maxreadpoolsize: Maximum number of Read links.
AutoStart: automatic restart.
localcachetime: Local cache expiry time in seconds.
Recordelog: Log is logged, this setting is only used to troubleshoot Redis runtime issues, such as Redis working properly, close the item.
The Redisconfiginfo class is a recording of Redis connection information, which echoes the Redisconfig in the configuration file. The CS code is as follows: (This piece of code is not written by myself, but I think it should be designed.) So, copy someone else's code. )
1 using System.Configuration;
2
3 namespace RedisDemo.Common.Redis
4 {
5 public sealed class RedisConfigInfo : ConfigurationSection
6 {
7 public static RedisConfigInfo GetConfig()
8 {
9 var section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
10 return section;
11 }
12 public static RedisConfigInfo GetConfig(string sectionName)
13 {
14 var section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
15 if (section == null)
16 {
17 throw new ConfigurationErrorsException("Section " + sectionName + " is not found.");
18 }
19 return section;
20 }
21 /// <summary>
22 /// Writable Redis Link Address
23 /// </summary>
24 [ConfigurationProperty("WriteServerList", IsRequired = false)]
25 public string WriteServerList
26 {
27 get
28 {
29 return (string)base["WriteServerList"];
30 }
31 set
32 {
33 base["WriteServerList"] = value;
34 }
35 }
36 /// <summary>
37 /// Readable Redis Link Address
38 /// </summary>
39 [ConfigurationProperty("ReadServerList", IsRequired = false)]
40 public string ReadServerList
41 {
42 get
43 {
44 return (string)base["ReadServerList"];
45 }
46 set
47 {
48 base["ReadServerList"] = value;
49 }
50 }
51 /// <summary>
52 /// Maximum number of write links
53 /// </summary>
54 [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)]
55 public int MaxWritePoolSize
56 {
57 get
58 {
59 var maxWritePoolSize = (int)base["MaxWritePoolSize"];
60 return maxWritePoolSize > 0 ? maxWritePoolSize : 5;
61 }
62 set
63 {
64 base["MaxWritePoolSize"] = value;
65 }
66 }
67 /// <summary>
68 /// Maximum number of read links
69 /// </summary>
70 [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)]
71 public int MaxReadPoolSize
72 {
73 get
74 {
75 var maxReadPoolSize = (int)base["MaxReadPoolSize"];
76 return maxReadPoolSize > 0 ? maxReadPoolSize : 5;
77 }
78 set
79 {
80 base["MaxReadPoolSize"] = value;
81 }
82 }
83 /// <summary>
84 /// Automatic restart
85 /// </summary>
86 [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)]
87 public bool AutoStart
88 {
89 get
90 {
91 return (bool)base["AutoStart"];
92 }
93 set
94 {
95 base["AutoStart"] = value;
96 }
97 }
98 /// <summary>
99 /// Local cache expiration time, in seconds
100 /// </summary>
101 [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)]
102 public int LocalCacheTime
103 {
104 get
105 {
106 return (int)base["LocalCacheTime"];
107 }
108 set
109 {
110 base["LocalCacheTime"] = value;
111 }
112 }
113 /// <summary>
114 /// Whether to log, this setting is only used to troubleshoot problems when redis is running. If redis works normally, please close the item.
115 /// </summary>
116 [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)]
117 public bool RecordeLog
118 {
119 get
120 {
121 return (bool)base["RecordeLog"];
122 }
123 set
124 {
125 base["RecordeLog"] = value;
126 }
127 }
128 }
129 }
The Redismanager class primarily creates a link pool management object.
1 using System.Linq;
2 using ServiceStack.Redis;
3 using System.Collections.Generic;
4
5 namespace RedisDemo.Common.Redis
6 {
7 public class RedisManager
8 {
9 /// <summary>
10 /// redis configuration file information
11 /// </summary>
12 private static readonly RedisConfigInfo RedisConfigInfo = RedisConfigInfo.GetConfig();
13
14 private static PooledRedisClientManager _prcm;
15
16 /// <summary>
17 /// Static constructor, initialize the link pool management object
18 /// </summary>
19 static RedisManager()
20 {
21 CreateManager();
twenty two }
twenty three
24 /// <summary>
25 /// Create a link pool management object
26 /// </summary>
27 private static void CreateManager()
28 {
29 var writeServerList = SplitString(RedisConfigInfo.WriteServerList, ",");
30 var readServerList = SplitString(RedisConfigInfo.ReadServerList, ",");
31
32 _prcm = new PooledRedisClientManager(writeServerList, readServerList,
33 new RedisClientManagerConfig
34 {
35 MaxWritePoolSize = RedisConfigInfo.MaxWritePoolSize,
36 MaxReadPoolSize = RedisConfigInfo.MaxReadPoolSize,
37 AutoStart = RedisConfigInfo.AutoStart,
38 });
39 }
40
41 private static IEnumerable<string> SplitString(string strSource, string split)
42 {
43 return strSource.Split(split.ToArray());
44 }
45
46 /// <summary>
47 /// Client cache operation object
48 /// </summary>
49 public static IRedisClient GetClient()
50 {
51 if (_prcm == null)
52 {
53 CreateManager();
54 }
55 return _prcm.GetClient();
56 }
57
58 }
59 }
actual combat: Encapsulates the code for REDIS operations on hash tables
In actual combat, we have to operate Redis is best to encapsulate the refining. The purpose of refinement is to reuse the code later. The benefits of code encapsulation reuse I won't say much, this is not the main discussion. Here are the pieces of code that I used in my project, some of which I have modified and posted to let you see. Personal feeling good: ^_^
The Redisoperatorbase class, the base class for Redis operations, inherits from the IDisposable interface and is primarily used to free memory.
1 using System;
2 using ServiceStack.Redis;
3
4 namespace RedisDemo.Common.Redis.RedisOperator
5 {
6 public abstract class RedisOperatorBase : IDisposable
7 {
8 protected IRedisClient Redis { get; private set; }
9 private bool _disposed = false;
10 protected RedisOperatorBase()
11 {
12 Redis = RedisManager.GetClient();
13 }
14 protected virtual void Dispose(bool disposing)
15 {
16 if (!this._disposed)
17 {
18 if (disposing)
19 {
20 Redis.Dispose();
21 Redis = null;
twenty two }
twenty three }
24 this._disposed = true;
25 }
26 public void Dispose()
27 {
28 Dispose(true);
29 GC.SuppressFinalize(this);
30 }
31 /// <summary>
32 /// Save the data DB file to the hard disk
33 /// </summary>
34 public void Save()
35 {
36 Redis.Save();
37 }
38 /// <summary>
39 /// Asynchronously save data DB files to hard disk
40 /// </summary>
41 public void SaveAsync()
42 {
43 Redis.SaveAsync();
44 }
45 }
}
The Hashoperator class is the Operation hash table class. Inherits from the Redisoperatorbase class, the code has the detailed comment, the understanding is clear.
1 using System;
2 using System.Collections.Generic;
3 using ServiceStack.Text;
4
5 namespace RedisDemo.Common.Redis.RedisOperator
6 {
7 public class HashOperator : RedisOperatorBase
8 {
9 public HashOperator() : base() { }
10 /// <summary>
11 /// Determine if a data has been cached
12 /// </summary>
13 public bool Exist<T>(string hashId, string key)
14 {
15 return Redis.HashContainsEntry(hashId, key);
16 }
17 /// <summary>
18 /// Store data to hash table
19 /// </summary>
20 public bool Set<T>(string hashId, string key, T t)
twenty one {
22 var value = JsonSerializer.SerializeToString<T>(t);
23 return Redis.SetEntryInHash(hashId, key, value);
twenty four }
25 /// <summary>
26 /// Remove a value from the hash
27 /// </summary>
28 public bool Remove(string hashId, string key)
29 {
30 return Redis.RemoveEntryFromHash(hashId, key);
31 }
32 /// <summary>
33 /// Remove the entire hash
34 /// </summary>
35 public bool Remove(string key)
36 {
37 return Redis.Remove(key);
38 }
39 /// <summary>
40 /// Get data from the hash table
41 /// </summary>
42 public T Get<T>(string hashId, string key)
43 {
44 string value = Redis.GetValueFromHash(hashId, key);
45 return JsonSerializer.DeserializeFromString<T>(value);
46 }
47 /// <summary>
48 /// Get the data of the entire hash
49 /// </summary>
50 public List<T> GetAll<T>(string hashId)
51 {
52 var result = new List<T>();
53 var list = Redis.GetHashValues(hashId);
54 if (list != null && list.Count > 0)
55 {
56 list.ForEach(x =>
57 {
58 var value = JsonSerializer.DeserializeFromString<T>(x);
59 result.Add(value);
60 });
61 }
62 return result;
63 }
64 /// <summary>
65 /// Set cache expiration
66 /// </summary>
67 public void SetExpire(string key, DateTime datetime)
68 {
69 Redis.ExpireEntryAt(key, datetime);
70 }
71 }
72 }
actual combat: Redis operation Hash Hash table additions and deletions to search
Originally intended this part of my demo in the operation code, think, all is the code, look at all annoying, it is better to explain this part of the operation corresponds to the Redis client Operation command. Another reason is that the hash operation has been divided, in fact, if the code is called to call the encapsulated code. Feel no meaning, I believe everyone will call. There's nothing to talk about. So next I'll say, the code above encapsulates the corresponding relationship to the client operation.
Exist<t> method: Corresponds to the hexists of the Redis operation. Returns whether the field is a field that exists in the hash set specified by key. True: false exists: not present
Set<t> method: Corresponds to the hget of the Redis operation. Sets the value of the specified field in the specified hash set of key. If the hash set specified by key does not exist, a new hash set is created and associated with the key. If the field exists in the hash set, it will be overridden.
Remove (string Hashid, String key) method: corresponds to the hdel of the Redis operation. Removes the specified domain from the hash set specified by key. Fields that do not exist in the hash set are ignored. If the hash set specified by key does not exist, it will be considered an empty hash set, and the command will return false.
Remove (String key) method: The Del that corresponds to the redis operation. Delete key directly.
Get<t> method: Corresponds to the hget of the Redis operation. Returns the value associated with the field.
Getall<t> method: Corresponds to the hvals of the Redis operation. Gets a list of the values in the hash set and returns an empty list when the hash sets specified by key do not exist.
Setexpire method: Corresponds to the expire of the Redis operation. Set cache expiration.
Summarize
Redis operations are many, in fact, encapsulation, but also just encapsulate some of the common operations. Interested friends can use the Anti-compilation tool to see the source code, you can know that all operations correspond to the Redis operation command. In fact, I personally think that using C # operations Redis is only a language need, we still have to learn its client operation. Development, many times the debugging is very slow, we can directly through the Redis client operation to find, so the efficiency will be a bit higher. And when the command is skilled, you will find that the client operation is much faster than the debug operation. Therefore, it is recommended that you use client operations more. At first you will feel a lot of need to remember, practice makes perfect, more operation, nature will be very good.
"Go" in C # using Redis Learning II using Redis hash in. NET4.5