C#操作Redis存储基础(续一)

上篇文章介绍了最基本的C#操纵Redis的方法,因为自己也在学习中,也是找资料学习,然后自己写,自己理解,也一直在补充,今天看一下比较高级的一点的用法,针对初学者哈。
这里我还是用的winform写的,还是framwork3.5的哈。看过上篇博文的知道,对于服务器端口,ID,过期时间等都是在代码中硬编码写的,相信现在在开发中你这样写你经理你同事一大堆他们得拿刀卸了你,所以一般都写在配置文件里,然后读取配置尽心连接,设置等,但是在配置文件中,没有专门得配置节让我们配置,咱们自己可以封装一个实体去存储配置。 

需要继承ConfigurationSection这个类,然后用ConfigurationProperty对配置节得属性做对照保存,然后读取配置,在配置文件中配置好之后,要做一下这个实体注册, 代码如下:

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

namespace RedisDemo
{
    public sealed class RedisConfigInfo : ConfigurationSection
    {

        #region   配置文件中属性定义
        /// 
        /// 可写的Redis链接地址
        /// 
        [ConfigurationProperty("WriteServerList", IsRequired = false)]
        public string WriteServerList
        {

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

        }
        /// 
        /// 可读的Redis链接地址
        /// 
        [ConfigurationProperty("ReadServerList", IsRequired = false)]
        public string ReadServerList
        {
            get
            {
                return (string)base["ReadServerList"];
            }
            set
            {
                base["ReadServerList"] = value;
            }
        }

        /// 
        /// 最大写链接数
        /// 
        [ConfigurationProperty("MaxWritePoolSize", IsRequired = false, DefaultValue = 5)]
        public int MaxWritePoolSize
        {
            get
            {
                int _maxWritePoolSize = (int)base["MaxWritePoolSize"];
                return _maxWritePoolSize > 0 ? _maxWritePoolSize : 5;
            }
            set
            {
                base["MaxWritePoolSize"] = value;
            }
        }

        /// 
        /// 最大读链接数
        /// 
        [ConfigurationProperty("MaxReadPoolSize", IsRequired = false, DefaultValue = 5)]
        public int MaxReadPoolSize
        {
            get
            {
                int _maxReadPoolSize = (int)base["MaxReadPoolSize"];
                return _maxReadPoolSize > 0 ? _maxReadPoolSize : 5;
            }
            set
            {
                base["MaxReadPoolSize"] = value;
            }
        }

        /// 
        /// 自动重启
        /// 
        [ConfigurationProperty("AutoStart", IsRequired = false, DefaultValue = true)]
        public bool AutoStart
        {
            get
            {
                return (bool)base["AutoStart"];
            }
            set
            {
                base["AutoStart"] = value;
            }
        }


        /// 
        /// 本地缓存到期时间,单位:秒
        /// 
        [ConfigurationProperty("LocalCacheTime", IsRequired = false, DefaultValue = 36000)]
        public int LocalCacheTime
        {
            get
            {
                return (int)base["LocalCacheTime"];
            }
            set
            {
                base["LocalCacheTime"] = value;
            }
        }

        /// 
        /// 是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项
        /// 
        [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;
        }

    }
}


<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>

上面这些配置读取做好了,就该做C#操作Redis服务器的帮助类了,比如创建客户端,解析配置文件的配置信息,跟ADO.NET那一套一样,都有个流程性的东西,写来写去一样,我也是按着别人的例子写的:

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();
        //缓存客户端
        public static PooledRedisClientManager prcm;


        //缓存初始化
        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();
        }

    }
}

完事儿就是调用啦,界面很简单:按钮1 其实没做什么事儿,刚开始为测试连接成功不成功用,新增 删除就不用解释了,
下面的那个黑黑的是个列表。C#操作Redis存储基础(续一)_第1张图片

一个User类,一个UserGroup类做实体模拟用户与用户组的业务,增删改查等,结合linq,操作起来也是方便的不要不要的了。

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; }
    }
}

代码里木有有注释,但看着方法名也清楚啦,看着代码,然后调试模式走一遍,比我码字清晰,而且易懂。我代码里就一行注释,那个地方是个坑,因为时间不早了急着睡觉还要出差,就直接用文本框的内容当作id先传进去了,正确的方法应该是根据文本框的信息查询出这条信息,然后把这条信息的ID传进去。(这里的ID,是Redis数据库中的系统自增长的那个ID哦,跟oracle中的Sequence差不多啦,代码中那个GetNextSequence就是获取下个自增长的数啦)

我Form1中的实现代码如下啦:

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();
            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 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");//此处为Redis的存储路径


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

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

                var userToInsert = new User
                {
                    UserID = user.GetNextSequence(),
                    UserName = textBox3.Text,
                    userGroup = new UserGroup { GroupID = redisClient.GetTypedClient().GetNextSequence(), GroupName = textBox2.Text }
                };
                user.Store(userToInsert);
                dataGridView1.DataSource = null;
                List 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();
                if (user.GetAll().Count > 0)
                {
                    List list = user.GetAll().ToList();
                    dataGridView1.DataSource = list;
                }
            }
        }

        void Insert()
        {

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

                var userToInsert = new User
                {
                    UserID = user.GetNextSequence(),
                    UserName = textBox3.Text,
                    userGroup = new UserGroup { GroupID = redisClient.GetTypedClient().GetNextSequence(), GroupName = textBox2.Text }
                };
                user.Store(userToInsert);
                dataGridView1.DataSource = null;
                List 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.DeleteById(textBox3.Text);   //实际应该是ID  此处应该报错????

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


        void Search()
        {

            using (var redisClient = RedisManager.GetRedisClient())
            {
                var user = redisClient.GetTypedClient();
                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)
        {

        }
    }
}

你可能感兴趣的:(redis初级教程)