I have a distributed system where In one place i insert around 10000 items in a redis list then Call my multiple applications hook to process items. what i need is to Have some ListLeftPop type of methhod with numbers of items. It should remove items from the redis List and return to my calling application.
I am using Stackexchange.Resis.extension
My current method just for get (not pop) is
public static List<T> GetListItemRange<T>(string key, int start, int chunksize) where T : class
{
List<T> obj = default(List<T>);
try
{
if (Muxer != null && Muxer.IsConnected && Muxer.GetDatabase() != null)
{
var cacheClient = new StackExchangeRedisCacheClient(Muxer, new NewtonsoftSerializer());
var redisValues = cacheClient.Database.ListRange(key, start, (start + chunksize - 1));
if (redisValues.Length > 0)
{
obj = Array.ConvertAll(redisValues, value => JsonConvert.DeserializeObject<T>(value)).ToList();
}
}
}
catch (Exception ex)
{
Logger.Fatal(ex.Message, ex);
}
return obj;
}
For Pop and get i have find a snippet
var cacheClient = new StackExchangeRedisCacheClient(Muxer, new NewtonsoftSerializer());
var redisValues = cacheClient.ListGetFromRight<T>(key);
But it will only do for single item
I assume that you are working on a queue, where you insert 1000 items at a single place and retrieve them at multiple place in the order at which it is inserted.
You can't achieve it with a single command but you can do it with 2 commands. You can write a lua script to make them atomic.
Lrange : http://redis.io/commands/lrange
This will list you first 100 elements in the list. here the offset is -100. Note that this will return the items in the opposite order at which it is inserted. So you need to reverse the loop to ensure the queue mechanism.
Ltrim : http://redis.io/commands/ltrim
This will trim the 1st 100 elements in the list. here 101 is n+1 so it must be 101. Here offset is 101
Writing them inside a lua block will ensure you the atomicity.
Let me give you a simple example.
return them to your code, now the result you want is 1 2 3 4 5 but what you have got is 5 4 3 2 1. So you need to reverse the loop and perform the operation.
When the next client comes in it will get the next set of values.
In this way you can achieve your requirement. Hope this helps.
EDIT:
Lua script:
Thanks Karthikeyan. My C# code with redis is as following
Now just doing a tweak that when the list is empty remove the redis Key