C# 使用redis实现把一个List类对象,整个存储起来,类中第一个字段是主键,并且可以更新后面的值

一、描述: C#使用redis实现把一个List类对象,整个存储起来,类中第一个字段是主键,后面两个分别是计算不同的数值,并且我后面每次可以根据主键更新两个值

二、实现

1. 引入相关包:

StackExchange.Redis

 

2. 相关的示例:

using StackExchange.Redis;
using System;
using System.Collections.Generic;

public class MyClass
{
    public string Key { get; set; }
    public int Value1 { get; set; }
    public int Value2 { get; set; }
}

public class RedisExample
{
    private static ConnectionMultiplexer redis;

    public static void Main(string[] args)
    {
        redis = ConnectionMultiplexer.Connect("localhost"); // 连接到本地Redis服务器

        var myList = new List<MyClass>
        {
            new MyClass { Key = "1", Value1 = 10, Value2 = 20 },
            new MyClass { Key = "2", Value1 = 30, Value2 = 40 },
            new MyClass { Key = "3", Value1 = 50, Value2 = 60 }
        };

        // 将List类对象存储到Redis中
        StoreListInRedis(myList);

        // 根据主键更新两个值
        UpdateValuesInRedis("2", 100, 200);

        // 从Redis中获取更新后的List类对象
        var updatedList = GetListFromRedis();

        // 打印更新后的List类对象
        foreach (var item in updatedList)
        {
            Console.WriteLine($"Key: {item.Key}, Value1: {item.Value1}, Value2: {item.Value2}");
        }
    }

    public static void StoreListInRedis(List<MyClass> list)
    {
        var db = redis.GetDatabase();

        foreach (var item in list)
        {
            var hashEntries = new HashEntry[]
            {
                new HashEntry("Value1", item.Value1),
                new HashEntry("Value2", item.Value2)
            };

            db.HashSet(item.Key, hashEntries);
        }
    }

    public static void UpdateValuesInRedis(string key, int newValue1, int newValue2)
    {
        var db = redis.GetDatabase();

        var hashEntries = new HashEntry[]
        {
            new HashEntry("Value1", newValue1),
            new HashEntry("Value2", newValue2)
        };

        db.HashSet(key, hashEntries);
    }

    public static List<MyClass> GetListFromRedis()
    {
        var db = redis.GetDatabase();
        var keys = redis.GetServer("localhost").Keys();

        var list = new List<MyClass>();

        foreach (var key in keys)
        {
            var hashEntries = db.HashGetAll(key);
            var item = new MyClass { Key = key };

            foreach (var hashEntry in hashEntries)
            {
                if (hashEntry.Name == "Value1")
                {
                    item.Value1 = (int)hashEntry.Value;
                }
                else if (hashEntry.Name == "Value2")
                {
                    item.Value2 = (int)hashEntry.Value;
                }
            }

            list.Add(item);
        }

        return list;
    }
}

3. 相关解释:

1. 其中的localhost配置文件应该怎么填?
是对应服务器的IP:端口,比如:106.54.75.88:6379,password=123456,defaultDatabase=0,connectTimeout=5000,syncTimeout=1000

以上就是相关的示例,谢谢学习!!!

 

posted @ 2023-07-16 20:56  锦大大的博客呀!  阅读(728)  评论(0编辑  收藏  举报