Aniket K
Aniket K

Reputation: 69

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?

Upvotes: 5

Views: 15458

Answers (4)

David
David

Reputation: 743

Can't you use ListRightPush?

using StackExchange.Redis;

// Connect to Redis
var redis = ConnectionMultiplexer.Connect("localhost");

// Get a reference to the Redis database
var db = redis.GetDatabase();

// Append an item to the end of the list
db.ListRightPush("mylist", "newitem");

Upvotes: 0

Raoul
Raoul

Reputation: 45

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

Upvotes: 3

Andrei
Andrei

Reputation: 44680

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

Upvotes: 10

Leonardo
Leonardo

Reputation: 11401

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

Upvotes: 0

Related Questions