Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 290
Aniket K Avatar asked Mar 09 '23 05:03

Aniket K


2 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");
like image 85
Andrei Avatar answered Mar 11 '23 19:03

Andrei


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.

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");
        }
like image 29
Raoul Avatar answered Mar 11 '23 19:03

Raoul