I am using StackExchange.Redis (Version 1.2.1) with an ASP.NET MVC C# application. I am able to store and view arrays and strings using 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?
-
2Could you please show us what you have tried so far with code?John Odom– John Odom2017-04-28 12:32:22 +00:00Commented Apr 28, 2017 at 12:32
-
Shouldn't this be exactly the same as with arrays?Andrei– Andrei2017-04-28 12:38:25 +00:00Commented Apr 28, 2017 at 12:38
-
What actual problem are you experiencing? There's no limitation here. Redis can store anything that can be serialized, and a list definitely can be serialized. Perhaps the problem is not the list, but the contained type that's stored in the list.Chris Pratt– Chris Pratt2017-04-28 13:02:45 +00:00Commented Apr 28, 2017 at 13:02
4 Answers
I recommend you to use StackExchange.Redis.Extensions, then you can do this:
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");
3 Comments
Add and Get<T> are not supported by IDatabase (github.com/StackExchange/StackExchange.Redis/blob/master/…). You're probably working with a wrapper around the API... check the basics: stackexchange.github.io/StackExchange.Redis/BasicsFast 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.
There is "StackExchange.Redis.Extensions.Core" and it allows to store & retrieve as below. Use this nuget with "StackExchange.Redis.Extensions.AspNetCore" and "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");
}
Comments
Strictly speaking, Redis only stores strings, and a List<MyObject>, is obviously not a string. 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. When retrieving, just de-serialize it...