C# Operation Redis Storage Base (Continuation 1)

Keywords: Redis xml encoding Database

The last article introduced the most basic method of C# manipulation of Redis, because I am learning, but also looking for information to learn, and then I write, understand, and have been supplementing, today to see a more advanced point of usage, for beginners Ha.
Here I'm still using winform, or framwork 3.5. As you know from the previous blog, the server port, ID, expiration time and so on are hard-coded in the code. I believe that in the development now you write like this, your manager and your colleagues have a lot of knives to unload you, so they usually write in the configuration file, and then read the configuration to connect, set up, etc., but in the configuration. In the file, there is no special configuration section for us to configure. We can encapsulate an entity to store the configuration ourselves. 

You need to inherit the Configuration Section class, then use Configuration Property to save the configuration savings properties, and read the configuration. After configuring the configuration file, you need to register the entity. The code is as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;

namespace RedisDemo
{
    public sealed class RedisConfigInfo : ConfigurationSection
    {

        #region   Property Definition in Configuration File
        /// <summary>
        /// Writable Redis Link Address
        /// </summary>
        [ConfigurationProperty("WriteServerList", IsRequired = false)]
        public string WriteServerList
        {

            get
            {
                return (string)base["WriteServerList"];
            }
            set
            {
                base["WriteServerList"] = value;
            }

        }
        /// <summary>
        /// Readable Redis Link Address
        /// </summary>
        [ConfigurationProperty("ReadServerList", IsRequired = false)]
        public string ReadServerList
        {
            get
            {
                return (string)base["ReadServerList"];
            }
            set
            {
                base["ReadServerList"] = value;
            }
        }

        /// <summary>
        /// Maximum number of write links
        /// </summary>
        [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)]
        public int MaxWritePoolSize
        {
            get
            {
                int _maxWritePoolSize = (int)base["MaxWritePoolSize"];
                return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5;
            }
            set
            {
                base["MaxWritePoolSize"] = value;
            }
        }

        /// <summary>
        /// Maximum number of links read
        /// </summary>
        [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)]
        public int MaxReadPoolSize
        {
            get
            {
                int _maxReadPoolSize = (int)base["MaxReadPoolSize"];
                return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5;
            }
            set
            {
                base["MaxReadPoolSize"] = value;
            }
        }

        /// <summary>
        /// Automatic restart
        /// </summary>
        [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)]
        public bool AutoStart
        {
            get
            {
                return (bool)base["AutoStart"];
            }
            set
            {
                base["AutoStart"] = value;
            }
        }


        /// <summary>
        /// Local cache expiration time, unit:second
        /// </summary>
        [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)]
        public int LocalCacheTime
        {
            get
            {
                return (int)base["LocalCacheTime"];
            }
            set
            {
                base["LocalCacheTime"] = value;
            }
        }

        /// <summary>
        /// Whether to log or not,This setting is only used for checking redis Runtime problems,as redis Working normally,Please close this item
        /// </summary>
        [ConfigurationProperty("RecordeLog", IsRequired = false, DefaultValue = false)]
        public bool RecordeLog
        {
            get
            {
                return (bool)base["RecordeLog"];
            }
            set
            {
                base["RecordeLog"] = value;
            }
        }
        #endregion




        public static RedisConfigInfo GetConfig()
        {
            RedisConfigInfo section = (RedisConfigInfo)ConfigurationManager.GetSection("RedisConfig");
            return section;
        }

    }
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="RedisConfig" type="RedisDemo.RedisConfigInfo, RedisDemo"/>
  </configSections>
  <RedisConfig WriteServerList="127.0.0.1:6379"
               ReadServerList="127.0.0.1:6379"
               MaxWritePoolSize="60"
               MaxReadPoolSize="60"
               AutoStart="true"
               LocalCacheTime="180" 
               RecordeLog="false">
  </RedisConfig>

</configuration>

After reading these configurations, it's time to do the help classes of C# operation of Redis server, such as creating client, parsing configuration information of configuration file. Like ADO.NET, there is a flow of things to write and write, and I also write according to other people's examples:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


using ServiceStack.Redis;

namespace RedisDemo
{
    public class RedisManager
    {
        public static RedisConfigInfo info = RedisConfigInfo.GetConfig();
        //Cache Client
        public static PooledRedisClientManager prcm;


        //Cache initialization
        static RedisManager()
        {
            CreatRedisManager();
        }
        public static void CreatRedisManager()
        {
            string[] writeServerList = SplitString(info.WriteServerList, ",");
            string[] readServerList = SplitString(info.ReadServerList, ",");

            prcm = new PooledRedisClientManager(readServerList, writeServerList,
                             new RedisClientManagerConfig
                             {
                                 MaxWritePoolSize = info.MaxWritePoolSize,
                                 MaxReadPoolSize = info.MaxReadPoolSize,
                                 AutoStart = info.AutoStart,
                             });
        }
        private static string[] SplitString(string strSource, string split)
        {
            return strSource.Split(split.ToArray());
        }


        public static IRedisClient GetRedisClient()
        {
            if (prcm == null)
            {
                CreatRedisManager();
            }
            return prcm.GetClient();
        }

    }
}

The interface is simple: button 1 doesn't actually do anything. At first, it was unsuccessful to test the connection, so there is no need to explain the new deletion.
The black and black one below is a list.

A User class, a User Group class to do entity simulation user and user group business, add, delete, modify, check, etc., combined with linq, operation is also convenient do not need.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedisDemo.Models
{
    public class User
    {
        public long UserID { get; set; }
        public string UserName { get; set; }
        public UserGroup userGroup { get; set; }
    }
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedisDemo.Models
{
    public class UserGroup
    {
        public long GroupID { get; set; }
        public string GroupName { get; set; }
    }
}

There are annotations in the code, but look at the method name is also clear, look at the code, and then debug mode to go through, clearer than my codeword, and easy to understand. In my code, there is a line of comments. That place is a pit. Because the time is not too early, I need to go to bed and go on business. I use the content of the text box as ID to pass in. The correct way is to query the information according to the information of the text box, and then pass in the ID of the information. (The ID here is the ID of the system growing in Redis database, which is similar to the Sequence in oracle, and the GetNextSequence in the code is the next self-increasing number.)

The implementation code in my Form1 is as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using RedisDemo.Models;

namespace RedisDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //var aaa = RedisConfigInfo.GetConfig();

        }

        private void New_Click(object sender, EventArgs e)
        {
            var redisClient = RedisManager.GetRedisClient();
            var user = redisClient.GetTypedClient<User>();
            var userToAdd = new User
            {
                UserID = user.GetNextSequence(),
                UserName = textBox3.Text,
                userGroup = new UserGroup { GroupID = 1L, GroupName = textBox2.Text }
            };
            user.Store(userToAdd);
            dataGridView1.DataSource = null;
            List<User> list = user.GetAll().ToList();
            dataGridView1.DataSource = list;
            label1.Text = list[1].userGroup.GroupName;
            redisClient.Dispose();
        }



        protected void button1_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("E:\\redis\\redis-server.exe");//Here is Redis's storage path


            using (var redisClient = RedisManager.GetRedisClient())
            {
                var user = redisClient.GetTypedClient<User>();

                if (user.GetAll().Count > 0)
                    user.DeleteAll();

                var userToInsert = new User
                {
                    UserID = user.GetNextSequence(),
                    UserName = textBox3.Text,
                    userGroup = new UserGroup { GroupID = redisClient.GetTypedClient<UserGroup>().GetNextSequence(), GroupName = textBox2.Text }
                };
                user.Store(userToInsert);
                dataGridView1.DataSource = null;
                List<User> list = user.GetAll().ToList();
                dataGridView1.DataSource = list;
                label1.Text = list[1].userGroup.GroupName;
            }
        }

        void GetAll(object sender, EventArgs e)
        {
            using (var redisClient = RedisManager.GetRedisClient())
            {
                var user = redisClient.GetTypedClient<User>();
                if (user.GetAll().Count > 0)
                {
                    List<User> list = user.GetAll().ToList();
                    dataGridView1.DataSource = list;
                }
            }
        }

        void Insert()
        {

            using (var redisClient = RedisManager.GetRedisClient())
            {
                var user = redisClient.GetTypedClient<User>();

                var userToInsert = new User
                {
                    UserID = user.GetNextSequence(),
                    UserName = textBox3.Text,
                    userGroup = new UserGroup { GroupID = redisClient.GetTypedClient<UserGroup>().GetNextSequence(), GroupName = textBox2.Text }
                };
                user.Store(userToInsert);
                dataGridView1.DataSource = null;
                List<User> list = user.GetAll().ToList();
                dataGridView1.DataSource = list;
                label1.Text = list[1].userGroup.GroupName;
            }
        }


        void Delete()
        {

            using (var redisClient = RedisManager.GetRedisClient())
            {
                var user = redisClient.GetTypedClient<User>();
                user.DeleteById(textBox3.Text);   //Actually, it should be ID. Should I report an error here?????

                if (user.GetAll().Count > 0)
                {
                    List<User> list = user.GetAll().ToList();
                    dataGridView1.DataSource = list;
                    label1.Text = list[1].userGroup.GroupName;
                }
            }
        }


        void Search()
        {

            using (var redisClient = RedisManager.GetRedisClient())
            {
                var user = redisClient.GetTypedClient<User>();
                var userList = user.GetAll().Where(x => x.userGroup.GroupName == textBox2.Text).ToList();

                if (userList.Count > 0)
                {
                    dataGridView1.DataSource = userList;
                    label1.Text = userList[0].userGroup.GroupName;
                }

            }
        }

        private void button1_Click_1(object sender, EventArgs e)
        {

        }
    }
}

Posted by Tsukasa on Mon, 01 Jul 2019 16:33:49 -0700