Redis在C#中的使用及Redis的封装

Redis是一款开源的、高性能的键-值存储(key-value store)。它常被称作是一款数据结构服务器(data structure server)。Redis的键值可以包括字符串(strings)、哈希(hashes)、列表(lists)、集合(sets)和 有序集合(sorted sets)等数据类型。 对于这些数据类型,你可以执行原子操作。例如:对字符串进行附加操作(append);递增哈希中的值;向列表中增加元素;计算集合的交集、并集与差集等。

为了获得优异的性能,Redis采用了内存中(in-memory)数据集(dataset)的方式。根据使用场景的不同,你可以每隔一段时间将数据集转存到磁盘上来持久化数据,或者在日志尾部追加每一条操作命令。

Redis同样支持主从复制(master-slave replication),并且具有非常快速的非阻塞首次同步(non-blocking first synchronization)、网络断开自动重连等功能。同时Redis还具有其它一些特性,其中包括简单的check-and-set机制、pub/sub和配置设置等,以便使得Redis能够表现得更像缓存(cache)。

Redis还提供了丰富的客户端,以便支持现阶段流行的大多数编程语言。详细的支持列表可以参看Redis官方文档:http://redis.io/clients。Redis自身使用ANSI C来编写,并且能够在不产生外部依赖(external dependencies)的情况下运行在大多数POSIX系统上,例如:Linux、*BSD、OS X和Solaris等。

Redis 由四个可执行文件:redis-benchmark、redis-cli、redis-server、redis-stat 这四个文件,加上一个redis.conf就构成了整个redis的最终可用包。它们的作用如下:

redis-server:Redis服务器的daemon启动程序

redis-cli:Redis命令行操作工具。当然,你也可以用telnet根据其纯文本协议来操作

redis-benchmark:Redis性能测试工具,测试Redis在你的系统及你的配置下的读写性能

redis-stat:Redis状态检测工具,可以检测Redis当前状态参数及延迟状况

首选,你先得开启redis-server,否则无法连接服务:

打开redis-server:

接下来你就可以调用Redis的属性来进行数据的存储及获取:

关键性代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ServiceStack.Redis;
using ServiceStack.Redis.Support;

namespace RedisStudy
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                //获取Redis操作接口
                IRedisClient Redis = RedisManager.GetClient();
                //Hash表操作
                HashOperator operators = new HashOperator();

                //移除某个缓存数据
                bool isTrue = Redis.Remove("additemtolist");

                //将字符串列表添加到redis
                List storeMembers = new List() { "韩梅梅", "李雷", "露西" };
                storeMembers.ForEach(x => Redis.AddItemToList("additemtolist", x));
                //得到指定的key所对应的value集合
                Console.WriteLine("得到指定的key所对应的value集合:");
                var members = Redis.GetAllItemsFromList("additemtolist");
                members.ForEach(s => Console.WriteLine("additemtolist :" + s));
                Console.WriteLine("");

                // 获取指定索引位置数据
                Console.WriteLine("获取指定索引位置数据:");
                var item = Redis.GetItemFromList("additemtolist", 2);
                Console.WriteLine(item);

                Console.WriteLine("");

                //将数据存入Hash表中
                Console.WriteLine("Hash表数据存储:");
                UserInfo userInfos = new UserInfo() { UserName = "李雷", Age = 45 };
                var ser = new ObjectSerializer();    //位于namespace ServiceStack.Redis.Support;
                bool results = operators.Set("userInfosHash", "userInfos", ser.Serialize(userInfos));
                byte[] infos = operators.Get("userInfosHash", "userInfos");
                userInfos = ser.Deserialize(infos) as UserInfo;
                Console.WriteLine("name=" + userInfos.UserName + "   age=" + userInfos.Age);

                Console.WriteLine("");

                //object序列化方式存储
                Console.WriteLine("object序列化方式存储:");
                UserInfo uInfo = new UserInfo() { UserName = "张三", Age = 12 };
                bool result = Redis.Set("uInfo", ser.Serialize(uInfo));
                UserInfo userinfo2 = ser.Deserialize(Redis.Get("uInfo")) as UserInfo;
                Console.WriteLine("name=" + userinfo2.UserName + "   age=" + userinfo2.Age);

                Console.WriteLine("");

                //存储值类型数据
                Console.WriteLine("存储值类型数据:");
                Redis.Set("my_age", 12);//或Redis.Set("my_age", 12);
                int age = Redis.Get("my_age");
                Console.WriteLine("age=" + age);

                Console.WriteLine("");

                //序列化列表数据
                Console.WriteLine("列表数据:");
                List userinfoList = new List {
                new UserInfo{UserName="露西",Age=1,Id=1},
                new UserInfo{UserName="玛丽",Age=3,Id=2},
            };
                Redis.Set("userinfolist_serialize", ser.Serialize(userinfoList));
                List userList = ser.Deserialize(Redis.Get("userinfolist_serialize")) as List;
                userList.ForEach(i =>
                {
                    Console.WriteLine("name=" + i.UserName + "   age=" + i.Age);
                });
                //释放内存
                Redis.Dispose();
                operators.Dispose();
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                Console.WriteLine("Please open the redis-server.exe ");
                Console.ReadKey();
            }
        }
    }
}

RedisManager类:

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

namespace RedisStudy
{
    ///
    /// RedisManager类主要是创建链接池管理对象的
    ///
    public class RedisManager
    {
        ///
        /// redis配置文件信息
        ///
        private static string RedisPath = System.Configuration.ConfigurationSettings.AppSettings["RedisPath"];
        private static PooledRedisClientManager _prcm;

        ///
        /// 静态构造方法,初始化链接池管理对象
        ///
        static RedisManager()
        {
            CreateManager();
        }

        ///
        /// 创建链接池管理对象
        ///
        private static void CreateManager()
        {
            _prcm = CreateManager(new string[] { RedisPath }, new string[] { RedisPath });
        }

        private static PooledRedisClientManager CreateManager(string[] readWriteHosts, string[] readOnlyHosts)
        {
            //WriteServerList:可写的Redis链接地址。
            //ReadServerList:可读的Redis链接地址。
            //MaxWritePoolSize:最大写链接数。
            //MaxReadPoolSize:最大读链接数。
            //AutoStart:自动重启。
            //LocalCacheTime:本地缓存到期时间,单位:秒。
            //RecordeLog:是否记录日志,该设置仅用于排查redis运行时出现的问题,如redis工作正常,请关闭该项。
            //RedisConfigInfo类是记录redis连接信息,此信息和配置文件中的RedisConfig相呼应

            // 支持读写分离,均衡负载
            return new PooledRedisClientManager(readWriteHosts, readOnlyHosts, new RedisClientManagerConfig
            {
                MaxWritePoolSize = 5, // "写"链接池链接数
                MaxReadPoolSize = 5, // "读"链接池链接数
                AutoStart = true,
            });
        }

        private static IEnumerable SplitString(string strSource, string split)
        {
            return strSource.Split(split.ToArray());
        }

        ///
        /// 客户端缓存操作对象
        ///
        public static IRedisClient GetClient()
        {
            if (_prcm == null)
            {
                CreateManager();
            }
            return _prcm.GetClient();
        }

    }
}


RedisOperatorBase类:

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

namespace RedisStudy
{
    ///
    /// RedisOperatorBase类,是redis操作的基类,继承自IDisposable接口,主要用于释放内存
    ///
    public abstract class RedisOperatorBase : IDisposable
    {
        protected IRedisClient Redis { get; private set; }
        private bool _disposed = false;
        protected RedisOperatorBase()
        {
            Redis = RedisManager.GetClient();
        }
        protected virtual void Dispose(bool disposing)
        {
            if (!this._disposed)
            {
                if (disposing)
                {
                    Redis.Dispose();
                    Redis = null;
                }
            }
            this._disposed = true;
        }
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        ///
        /// 保存数据DB文件到硬盘
        ///
        public void Save()
        {
            Redis.Save();
        }
        ///
        /// 异步保存数据DB文件到硬盘
        ///
        public void SaveAsync()
        {
            Redis.SaveAsync();
        }
    }
}

HashOperator类:

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

namespace RedisStudy
{
    ///
    /// HashOperator类,是操作哈希表类。继承自RedisOperatorBase类
    ///
    public class HashOperator : RedisOperatorBase
    {
        public HashOperator() : base() { }
        ///
        /// 判断某个数据是否已经被缓存
        ///
        public bool Exist(string hashId, string key)
        {
            return Redis.HashContainsEntry(hashId, key);
        }
        ///
        /// 存储数据到hash表
        ///
        public bool Set(string hashId, string key, T t)
        {
            var value = JsonSerializer.SerializeToString(t);
            return Redis.SetEntryInHash(hashId, key, value);
        }
        ///
        /// 移除hash中的某值
        ///
        public bool Remove(string hashId, string key)
        {
            return Redis.RemoveEntryFromHash(hashId, key);
        }
        ///
        /// 移除整个hash
        ///
        public bool Remove(string key)
        {
            return Redis.Remove(key);
        }
        ///
        /// 从hash表获取数据
        ///
        public T Get(string hashId, string key)
        {
            string value = Redis.GetValueFromHash(hashId, key);
            return JsonSerializer.DeserializeFromString(value);
        }
        ///
        /// 获取整个hash的数据
        ///
        public List GetAll(string hashId)
        {
            var result = new List();
            var list = Redis.GetHashValues(hashId);
            if (list != null && list.Count > 0)
            {
                list.ForEach(x =>
                {
                    var value = JsonSerializer.DeserializeFromString(x);
                    result.Add(value);
                });
            }
            return result;
        }
        ///
        /// 设置缓存过期
        ///
        public void SetExpire(string key, DateTime datetime)
        {
            Redis.ExpireEntryAt(key, datetime);
        }
    }
}

UserInfo类:

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

namespace RedisStudy
{
    [Serializable]
    public class UserInfo
    {
        public int Id;
        public string UserName;
        public int Age;
    }
}

app.config配置:


Original: https://www.cnblogs.com/jx270/p/6444075.html
Author: v.e.n.u.s
Title: Redis在C#中的使用及Redis的封装

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/529444/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

  • 关于Precision,Recall,ROC曲线,KS,Lift等模型评价指标的介绍

    1.Precision, Recall 准确率 (Accuracy = \frac{TP+TN}{TP+TN+FP+FN}) 精确率(或命中率) (Precision = \fra…

    Linux 2023年6月13日
    089
  • docker 容器大小查看及清理docker磁盘空间

    这篇文章最初是由博主创作的。请注明转载的来源: [En] This article is originally created by the blogger. Please ind…

    Linux 2023年5月27日
    096
  • 【数学建模相关】matplotlib画多个子图(散点图为例 左右对照画图)

    @ 例题 例图 代码展示 例题 乙醇偶合制备 C4 烯烃 C4 烯烃广泛应用于化工产品及医药的生产,乙醇是生产制备 C4 烯烃的原料。 在制备过程中,催化剂组合(即:Co 负载量、…

    Linux 2023年6月8日
    0154
  • Springboot 的一些默认配置规则

    本文样例说明仅适用 maven 环境和语法,但所述内容也适用 gradle 1. logback 日志默认为 slf4j + logback 框架,引入如下 jar 之后,就自动引…

    Linux 2023年6月6日
    084
  • DDoS攻击–Syn_Flood攻击防护详解(TCP)

    https://blog.csdn.net/qq_34777600/article/details/81946514 Original: https://www.cnblogs.c…

    Linux 2023年6月7日
    084
  • python向access插入数据,报语法错误的一个解决思路(-2147352567,’发生意外。’)

    工作中遇到一个古老的程序,数据库使用的事access,想用python批量导入数据,报” INSERT INTO 语句的语法错误”。 但是,将插入语句放到a…

    Linux 2023年6月14日
    078
  • Mysql实战技能全解

    一、数据库原理 1 数据的分类 结构化的数据:即有固定格式和有限长度的数据。例如填的表格就是结构化的数据,国籍:中华人民共和国,民族:汉,性别:男,这都叫结构化数据 非结构化的数据…

    Linux 2023年6月7日
    0141
  • wget命令8种实用用法

    大家好,我是良许。 wget 是一个可以从网络上下载文件的免费实用程序,它的工作原理是从 Internet 上获取数据,并将其保存到本地文件中或显示在你的终端上。 这实际上也是大家…

    Linux 2023年5月27日
    072
  • 如何入行软件开发——常见问题及岗位分工

    —— 你以为我每天上班就是为了几个臭钱么!? —— 是的,你说对了…… IT是一个有些让业外同行羡慕嫉妒恨的行业,统计数据来说平均薪资应当是仅次于金融行业的…

    Linux 2023年6月13日
    089
  • SSM中的拦截器

    SpringMVC的处理器拦截器类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。开发者可以自己定义一些拦截器来实现特定的功能。 过滤器与拦截器的区别…

    Linux 2023年6月14日
    085
  • 为Windows Service 2019 使用 Docker

    引言最近收到领导通知,甲方需要将原来的服务器迁移到新的服务器。原来的服务器上安装了很多的服务,每次重启之后总是有很多的问题需要人工大量的进行干预。这次迁移的还是Windows服务器…

    Linux 2023年6月14日
    0112
  • linux开机自动挂载(/etc/fstab)

    fatab 介绍 通常情况,Linux 的 /etc/fstab 文件可能有如下内容: # /etc/fstab Created by anaconda on Fri Aug 18…

    Linux 2023年6月7日
    0116
  • 2:数据和提取

    Mail 新的小插件 tldr tldr简化了烦琐的 man的输出帮助信息,只列出关键的语法信息、例子,方便用户使用。 npm install -g tldr vim 的语法 ^$…

    Linux 2023年6月7日
    078
  • 5.5 Vim移动光标命令汇总

    Vim 文本编辑器中,最简单的移动光标的方式是使用方向键,但这种方式的效率太低,更高效的方式使用快捷键。 Vim 移动光标常用的快捷键及其功能如下面各表所示,需要注意的是,表中所有…

    Linux 2023年6月7日
    0100
  • 惊了!修仙=编程??

    大家好,我是良许。 印象中,我们接触到的编程书籍都是这样的: 这样的书籍,去除阅读属性之后,还可以用来垫电脑屏幕、垫桌脚、盖泡面、砸产品经理,实乃居家、旅行、自卫必备神器! 这种书…

    Linux 2023年6月14日
    089
  • Linux下info page指令

    在所有的Unix Like系统当中,都可以利用man 来查询指令或者是相关文件的用法;但是,在Linux里面则又额外提供了一种在线求助的方法,那就是利用info这个好用的家伙啦!基…

    Linux 2023年6月8日
    084
亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球