简体   繁体   English

如何使用 StackExchange.Redis 存储列表?

[英]How can I store a list using StackExchange.Redis?

I am using StackExchange.Redis (Version 1.2.1) with an ASP.NET MVC C# application.我将StackExchange.Redis (1.2.1 版)与 ASP.NET MVC C# 应用程序一起使用。 I am able to store and view arrays and strings using StackExchange.Redis .我能够使用StackExchange.Redis存储和查看数组和字符串。 However, I am not able to figure out a way to store a list.但是,我无法找出存储列表的方法。 Is there any way to do it?有什么办法吗? If not can you please suggest some good alternatives to StackExchange.Redis to accomplish this requirement?如果没有,您能否建议StackExchange.Redis一些好的替代方案来完成此要求?

I recommend you to use StackExchange.Redis.Extensions , then you can do this:我建议你使用StackExchange.Redis.Extensions ,然后你可以这样做:

var list = new List<int> { 1, 2, 3 };
bool added = cacheClient.Add("MyList", list, DateTimeOffset.Now.AddMinutes(10));

And to retrieve your list:并检索您的列表:

var list = cacheClient.Get<List<int>>("MyList");

Strictly speaking, Redis only stores strings, and a List<MyObject> , is obviously not a string.严格来说,Redis 只存储字符串,而一个List<MyObject> ,显然不是字符串。 But there's a way to reliably achieve your goal: transform your list into a string.但是有一种方法可以可靠地实现您的目标:将您的列表转换为字符串。

To store a List<MyObject> , first serialize it as a string, using tools such as JsonConvert , then store it on redis.要存储List<MyObject> ,首先使用JsonConvert等工具将其序列化为字符串,然后将其存储在 redis 上。 When retrieving, just de-serialize it...检索时,只需将其反序列化...

Fast forward 3 years+ and I was looking to do similar in .NET core using StackExchange.Redis so leaving this here in case someone is looking to do the same.快进 3 年以上,我希望在 .NET 核心中使用 StackExchange.Redis 做类似的事情,所以留在这里以防万一有人想做同样的事情。

There is "StackExchange.Redis.Extensions.Core" and it allows to store & retrieve as below.有“StackExchange.Redis.Extensions.Core”,它允许存储和检索如下。 Use this nuget with "StackExchange.Redis.Extensions.AspNetCore" and "StackExchange.Redis.Extensions.Newtonsoft"将此 nuget 与“StackExchange.Redis.Extensions.AspNetCore”和“StackExchange.Redis.Extensions.Newtonsoft”一起使用

private readonly IRedisCacheClient _redisCacheClient;

public ValuesController(IRedisCacheClient redisCacheClient)
        {
            _redisCacheClient = redisCacheClient;
        }

public async Task<List<int>> Get()
        {
            var list = new List<int> { 1, 2, 3 };
            var added = await _redisCacheClient.Db0.AddAsync("MyList", list, DateTimeOffset.Now.AddMinutes(10));
            return await _redisCacheClient.Db0.GetAsync<List<int>>("MyList");
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM