Redis相关数据类型String,Set,SortedSet,List,Hash的使用

参考博客:https://www.runoob.com/redis/redis-data-types.html

Redis是一种键值对的内存数据库,在Windows中是一个Windows服务,类似于Mysql服务,Oracle服务。

全称:REmote DIctionary Server(Redis)

Redis 数据类型

Redis支持五种数据类型:string(字符串),hash(哈希,字典),list(列表),set(集合)及zset(sorted set:有序集合)。

注意:Redis支持多个数据库,并且每个数据库的数据是隔离的不能共享,并且基于单机才有,如果是集群就没有数据库的概念。

Redis是一个字典结构的存储服务器,而实际上一个Redis实例提供了多个用来存储数据的字典,客户端可以指定将数据存储在哪个字典中。这与我们熟知的在一个关系数据库实例中可以创建多个数据库类似,所以可以将其中的每个字典都理解成一个独立的数据库。

每个数据库对外都是一个从0开始的递增数字命名,Redis默认支持16个数据库(可以通过配置文件支持更多,无上限),可以通过配置databases来修改这一数字。客户端与Redis建立连接后会自动选择0号数据库,不过可以随时使用SELECT命令更换数据库

Redis的类型枚举

public enum RedisKeyType
    {
        None = 0,
        String = 1,
        List = 2,
        Set = 3,
        SortedSet = 4,
        Hash = 5
    }

Redis安装成功后,Windows+R,输入 services.msc 。可以查看redis是否已安装成功。

在安装目录下 有一个自带的客户端工具redis-cli.exe。双击打击,可以输入get, set, del, select 等命令来测试。如图:

下载ServiceStack类库。

VS2017中新建控制台项目RedisDemo【.net framework 4.5】。右键项目,选择“管理NuGet程序包”,在浏览中输入:ServiceStack.Redis。

选择ServiceStack.Redis,点击“安装”。如有许可,点击允许即可,等待安装完成。同时,会自动下载所需的Redis文件,项目也自动会添加对ServiceStack相关类库的引用【ServiceStack.Common】、【ServiceStack.Interfaces】、【ServiceStack.Redis】、【ServiceStack.Text】。

测试源程序如下:

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

namespace RedisDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.SetWindowSize(145, 55);
            //创建一个Redis客户端对象
            PooledRedisClientManager poolRedis = new PooledRedisClientManager(new string[] { "127.0.0.1:6379" }, new string[] { "127.0.0.1:6379" },
                new RedisClientManagerConfig()
                {
                    DefaultDb = 1,
                    MaxReadPoolSize = 50,
                    MaxWritePoolSize = 50,
                    AutoStart = true
                }, 1, 10, 3000);
            poolRedis.ConnectTimeout = 3000;
            IRedisClient redisClient = poolRedis.GetClient();
            Console.WriteLine($"打印Redis客户端实体数据类型:{redisClient.GetType()}");
            TestEntrance(RedisKeyType.String, TestString, redisClient);
            TestEntrance(RedisKeyType.List, TestList, redisClient);
            TestEntrance(RedisKeyType.Set, TestSet, redisClient);
            TestEntrance(RedisKeyType.SortedSet, TestSortedSet, redisClient);
            TestEntrance(RedisKeyType.Hash, TestHash, redisClient);
            Console.ReadLine();
        }

/// <summary>
        /// 统一测试入口
        /// </summary>
        /// <param name="redisKeyType"></param>
        /// <param name="action"></param>
        /// <param name="client"></param>
        static void TestEntrance(RedisKeyType redisKeyType, Action<IRedisClient> action, IRedisClient client)
        {
            Console.WriteLine($"测试【Redis数据类型:{redisKeyType}】的相应功能......");
            action(client);
        }

/// <summary>
        /// 测试Redis五大数据类型之一:【String】字符串
        /// </summary>
        /// <param name="client"></param>
        static void TestString(IRedisClient client)
        {
            client.Remove("T");
            bool addResult = client.Add("T", DateTime.Now);
            Console.WriteLine($"添加结果:{addResult}。当前值:{client.Get<DateTime>("T")},Redis键的类型:{client.GetEntryType("T")}");
            client.Set("T", new Employee()
            {
                Id = 1234,
                Name = "科加斯",
                JoinTime = DateTime.Now.AddYears(-3)
            });
            Console.WriteLine($"当前值:{client.Get<Employee>("T")},Redis键的类型:{client.GetEntryType("T")}");
            Console.WriteLine("【对已经存在的键,使用Add方法将添加失败,但不抛出异常】");
            addResult = client.Add("T", 15);
            Console.WriteLine($"添加结果:{addResult}。当前值:{client.Get<string>("T")},Redis键的类型:{client.GetEntryType("T")}");
            Console.WriteLine($"测试不存在的key的Redis类型:【{client.GetEntryType("NotExists")}】");
            Console.WriteLine();
        }

/// <summary>
        /// 测试Redis五大数据类型之一:【List】列表
        /// </summary>
        /// <param name="client"></param>
        static void TestList(IRedisClient client)
        {
            string listId = "listId";
            client.Lists[listId].Clear();
            Console.WriteLine("【List允许值相同】");
            Console.WriteLine($"List对应的数据类型:【{client.Lists[listId].GetType()}】");
            client.AddItemToList(listId, "张三");
            Console.WriteLine($"当前List数据个数【{client.Lists[listId].Count}】,对应数据:{string.Join(",", client.Lists[listId])}");
            client.AddItemToList(listId, "李四");
            Console.WriteLine($"当前List数据个数【{client.Lists[listId].Count}】,对应数据:{string.Join(",", client.Lists[listId])}");
            client.AddItemToList(listId, "张三");
            Console.WriteLine($"当前List数据个数【{client.Lists[listId].Count}】,对应数据:{string.Join(",", client.Lists[listId])}");
            Console.WriteLine();
        }

/// <summary>
        /// 测试Redis五大数据类型之一:【Set】集合
        /// </summary>
        /// <param name="client"></param>
        static void TestSet(IRedisClient client)
        {
            string setId = "setId";
            client.Sets[setId].Clear();
            Console.WriteLine("【Set不允许值相同,当值相同时,只保留第一个】");
            Console.WriteLine($"Set对应的数据类型:【{client.Sets[setId].GetType()}】");
            client.AddItemToSet(setId, "张三");
            Console.WriteLine($"当前Set数据个数【{client.Sets[setId].Count}】,对应数据:{string.Join(",", client.Sets[setId])}");
            client.AddItemToSet(setId, "李四");
            Console.WriteLine($"当前Set数据个数【{client.Sets[setId].Count}】,对应数据:{string.Join(",", client.Sets[setId])}");
            client.AddItemToSet(setId, "王五");
            Console.WriteLine($"当前Set数据个数【{client.Sets[setId].Count}】,对应数据:{string.Join(",", client.Sets[setId])}");
            client.AddItemToSet(setId, "李四");
            Console.WriteLine($"当前Set数据个数【{client.Sets[setId].Count}】,对应数据:{string.Join(",", client.Sets[setId])}");
            Console.WriteLine();
        }

/// <summary>
        /// 测试Redis五大数据类型之一:【SortedSet】有序集合
        /// </summary>
        /// <param name="client"></param>
        static void TestSortedSet(IRedisClient client)
        {
            string sortedSetId = "sortedSetId";
            client.SortedSets[sortedSetId].Clear();
            Console.WriteLine("【SortedSet不允许值相同,当值相同时,只保留最后一个(覆盖之前的分数)】,每加入一个元素都会依据分数进行重新排序");
            Console.WriteLine($"SortedSet对应的数据类型:【{client.SortedSets[sortedSetId].GetType()}】");
            client.AddItemToSortedSet(sortedSetId, "张三", 40);
            Console.WriteLine($"当前SortedSet数据个数【{client.SortedSets[sortedSetId].Count}】,对应数据:{string.Join(",", client.SortedSets[sortedSetId])}");
            foreach (string item in client.SortedSets[sortedSetId])
            {
                Console.WriteLine($"    集合项:【{item}】,分数:【{client.SortedSets[sortedSetId].GetItemScore(item)}】");
            }
            client.AddItemToSortedSet(sortedSetId, "李四", 20);
            Console.WriteLine($"当前SortedSet数据个数【{client.SortedSets[sortedSetId].Count}】,对应数据:{string.Join(",", client.SortedSets[sortedSetId])}");
            foreach (string item in client.SortedSets[sortedSetId])
            {
                Console.WriteLine($"    集合项:【{item}】,分数:【{client.SortedSets[sortedSetId].GetItemScore(item)}】");
            }
            client.AddItemToSortedSet(sortedSetId, "王五", 30);
            Console.WriteLine($"当前SortedSet数据个数【{client.SortedSets[sortedSetId].Count}】,对应数据:{string.Join(",", client.SortedSets[sortedSetId])}");
            foreach (string item in client.SortedSets[sortedSetId])
            {
                Console.WriteLine($"    集合项:【{item}】,分数:【{client.SortedSets[sortedSetId].GetItemScore(item)}】");
            }
            client.AddItemToSortedSet(sortedSetId, "李四", 35);
            Console.WriteLine($"当前SortedSet数据个数【{client.SortedSets[sortedSetId].Count}】,对应数据:{string.Join(",", client.SortedSets[sortedSetId])}");
            foreach (string item in client.SortedSets[sortedSetId])
            {
                Console.WriteLine($"    集合项:【{item}】,分数:【{client.SortedSets[sortedSetId].GetItemScore(item)}】");
            }
            client.AddItemToSortedSet(sortedSetId, "李四", 60);
            Console.WriteLine($"当前SortedSet数据个数【{client.SortedSets[sortedSetId].Count}】,对应数据:{string.Join(",", client.SortedSets[sortedSetId])}");
            foreach (string item in client.SortedSets[sortedSetId])
            {
                Console.WriteLine($"    集合项:【{item}】,分数:【{client.SortedSets[sortedSetId].GetItemScore(item)}】");
            }
            Console.WriteLine();
        }

/// <summary>
        /// 测试Redis五大数据类型之一:【Hash】哈希,字典
        /// </summary>
        /// <param name="client"></param>
        static void TestHash(IRedisClient client)
        {
            string hashId = "hashId";
            client.Hashes[hashId].Clear();
            Console.WriteLine("【Hash不允许键相同,当键相同时,只保留一个(SetEntryInHash:存在就覆盖,不存在就添加)、(SetEntryInHashIfNotExists:不存在键才增加,否则什么也不做)】");
            Console.WriteLine($"Hash对应的数据类型:【{client.Hashes[hashId].GetType()}】");
            bool addResult = client.SetEntryInHash(hashId, "越今朝", "落日部");
            Console.WriteLine($"添加结果:【{addResult}】.当前Hash数据个数【{client.Hashes[hashId].Count}】,对应数据:{string.Join(",", client.Hashes[hashId])}");
            addResult = client.SetEntryInHash(hashId, "洛昭言", "洛家庄");
            Console.WriteLine($"添加结果:【{addResult}】.当前Hash数据个数【{client.Hashes[hashId].Count}】,对应数据:{string.Join(",", client.Hashes[hashId])}");
            addResult = client.SetEntryInHash(hashId, "越今朝", "驭界枢");
            Console.WriteLine($"添加结果:【{addResult}】.当前Hash数据个数【{client.Hashes[hashId].Count}】,对应数据:{string.Join(",", client.Hashes[hashId])}");
            addResult = client.SetEntryInHash(hashId, "明绣", "与青山");
            Console.WriteLine($"添加结果:【{addResult}】.当前Hash数据个数【{client.Hashes[hashId].Count}】,对应数据:{string.Join(",", client.Hashes[hashId])}");
            addResult = client.SetEntryInHashIfNotExists(hashId, "越今朝", "乌岩村");
            Console.WriteLine($"添加结果:【{addResult}】.当前Hash数据个数【{client.Hashes[hashId].Count}】,对应数据:{string.Join(",", client.Hashes[hashId])}");
            Console.WriteLine();
        }
    }

/// <summary>
    /// 测试雇员类
    /// </summary>
    class Employee
    {
        /// <summary>
        /// 编号
        /// </summary>
        public int Id { get; set; }
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name { get; set; }
        /// <summary>
        /// 入职日期
        /// </summary>
        public DateTime JoinTime { get; set; }

/// <summary>
        /// 重写打印效果
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return $"编号:【{Id}】,姓名:【{Name}】,入职日期:【{JoinTime.ToString("yyyy-MM-dd")}】";
        }
    }
}

程序运行如图:

C#对Redis的读写与使用相关推荐

  1. php redis并发读写,PHP使用Redis实现防止大并发下二次写入的方法

    本文实例讲述了PHP使用Redis实现防止大并发下二次写入的方法.分享给大家供大家参考,具体如下: PHP调用redis进行读写操作,大并发下会出现:读取key1,没有内容则写入内容,但是大并发下会出 ...

  2. redis之读写分离

    写在前面 本文一起看下redis的读写分离架构. 1:为什么要读写分离 读写分离,即主库执行写请求,然后写的数据同步到从库,从库执行读请求,架构图如下: 一般读写分离带给我们的好处可能如下: 分担主库 ...

  3. java面试(二十五)--(1)redis为什么读写速率快性能好(2)说说web.xml文件中可以配置哪些内容(3)和的区别(4)扑克牌顺子

    1. redis为什么读写速率快性能好? 1.Redis将数据存储在内存上,避免了频繁的IO操作 2.Redis其本身采用字典的数据结构,时间复杂度为O(1),且其采用渐进式的扩容手段 3.Redis ...

  4. java hgetall_详解Java使用Pipeline对Redis批量读写(hmsethgetall)

    一般情况下,Redis Client端发出一个请求后,通常会阻塞并等待Redis服务端处理,Redis服务端处理完后请求命令后会将结果通过响应报文返回给Client. 感觉这有点类似于HBase的Sc ...

  5. redis主从读写分离replication复制数据+sentienl哨兵集群主备切换

    说明:最近公司在自己搭建了一套redis主从读写分离+sentinel哨兵集群主备切换,通过手工去搭建replication复制+主从架构+读写分离+哨兵集群+高可用redis集群架构 公司的已经搭建 ...

  6. Linux企业运维 6.6 -- Redis部署及主从切换、Redis+Mysql读写分离

    目录 Redis简介 redis的编译.安装 1.server1的redis配置 2.server2的redis安装 3.server3配置redis 三.redis主从复制 四.Sentine主从自 ...

  7. windows下Redis 主从读写分离部署

    windows下Redis 主从读写分离部署 原文: windows下Redis 主从读写分离部署 1.可直接下载window下的运行文件(下面这个链接) 也可以浏览github 查看相应的版本说明文 ...

  8. StackExchange.Redis客户端读写主从配置,以及哨兵配置

    今天简单分享一下StackExchange.Redis客户端中配置主从分离以及哨兵的配置. 关于哨兵如果有不了解的朋友,可以看我之前的一篇分享,当然主从复制文章也可以找到.http://www.cnb ...

  9. Redis主从读写分离配置

    环境描述: 主redis:192.168.10.1 6379 从redis:192.168.10.2 6380 一.主从配置 1.将主从redis配置文件redis.conf中的aemonize no ...

  10. redis的读写分离和主机宕机

    主写从读,读写分离 主:只允许写操作 从:只允许读操作 主机宕机,从机原地待命 主机宕机后,他的从机的状态会变成未启用,因为它要等他的老大,也就是主机正常运行后,它才工作 模拟一下 关闭主机的服务 r ...

最新文章

  1. 【转帖】OnPreRender Render的区别
  2. 解决远程连接超过最大连接数问题
  3. MAT之NSL:CPK_NN神经网络实现预测哪个样本与哪个样本处在同一层,从而科学规避我国煤矿突水灾难
  4. 012 分析技能冷却二叉树
  5. Java基于socket服务实现UDP协议的方法
  6. sql count为空时显示0_C0010负坐标显示为正数+红色0值参考线
  7. adobe怎么统计字数_统计数据显示,6 月份桌面 Linux 市场份额攀升至历史新高 | Linux 中国...
  8. Ignite 配置更新Oracle JDBC Drive
  9. 自动化运维之ansible-安装部署与基础命令篇
  10. 理发师问题报告java_操作系统-理发师问题的java模拟
  11. 简易RAM的C++实现
  12. 读取hdr图像_HDR和蓝光哪个更清晰?画质更好?
  13. http和https连接下载
  14. 浏览器兼容性问题解决方案 · 总结
  15. 2021牛客多校10 F Train Wreck(搜索,优先队列)
  16. Nodemailer 使用Gmail发送邮件
  17. Oracle的Replace函数与translate函数详解与比较
  18. vsual studio 如何关闭禁止mscorsvw.exe (转)
  19. linkkitapp log for debug
  20. 易基因|RNA m7G甲基化测序(m7G-MeRIP-seq)

热门文章

  1. JavaScript速成
  2. Telltale:简化了Netflix应用程序监视
  3. 【经验教程】google谷歌Gmail邮箱帐号被停用怎么恢复Gmail邮箱google谷歌账号?
  4. python中sys.argv的用法_python的sys.argv[]用法解释
  5. GDOI2017小结
  6. 知道一点怎么设直线方程_已知两点坐标怎样求直线方程
  7. 在ubuntu20.04中安装MATLAB时常见问题及解决方法
  8. 江苏大学计算机学院在职研究生,江苏大学电子与通信工程在职研究生招生简章...
  9. python-将csv转txt
  10. Python基础学习:operator模块