C#对Redis的读写与使用

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")}】";
        }
    }
}
 

程序运行如图:

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
C#使用Redis缓存可以通过使用RedisHelper类来实现。首先,你需要导入DeveloperSharp.Redis命名空间,然后可以使用该类提供的一些方法来存取字符串和对象数据。 对于存取字符串,你可以使用RedisHelper.SetStringKey方法存入一个字符串到Redis缓存中,例如: ``` RedisHelper.SetStringKey("MyText", "世界,你好"); ``` 然后,你可以使用RedisHelper.GetStringKey方法从Redis缓存中取出该字符串,例如: ``` string aa = RedisHelper.GetStringKey("MyText"); ``` 对于存取对象,你首先需要创建一个对象,例如: ``` teacher obj = new teacher { name = "王老师", age = 42 }; ``` 然后,使用RedisHelper.SetStringKey方法将该对象存入Redis缓存中,例如: ``` RedisHelper.SetStringKey("MyTeacher", obj); ``` 最后,你可以使用RedisHelper.GetStringKey<teacher>方法从Redis缓存中取出该对象,例如: ``` teacher t = RedisHelper.GetStringKey<teacher>("MyTeacher"); string Name = t.name; int Age = t.age; ``` 除了存取字符串和对象外,RedisHelper类还提供了很多其他常用功能,如批量缓存、过期时间设定、异步、哈希存储和有序集合存储等等。你可以查看RedisHelper类的其他方法来了解更多功能。 希望这些信息能够帮助到你。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [.NET/C#大型项目研发必备(11)--使用Redis缓存](https://blog.csdn.net/weixin_45237473/article/details/122695062)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [C# 使用Redis缓存](https://blog.csdn.net/qq_33678106/article/details/102916284)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

斯内科

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值