David
David

Reputation: 15360

How to create multiple sequence numbers when using a transaction with Redis ServiceStack

I'm trying to insert multiple new entities into Redis using C# ServiceStack. The problem I am having is generating the sequence numbers.

From what I've read you cannot make other requests whilst queueing the transaction commands to garauntee an atomic action.

This would then mean having to iterate over my entities collection to first generate the sequence numbers and then iterating again to queue the transaction commands and execute?

Is there an efficient way of doing this?

IRedisClientsManager RedisManager;

RedisManager.ExecTrans(x =>
{
    foreach (var entity in entities)
    {
        x.QueueCommand(c =>
        {
            //entity.Id = generate sequence number
            c.Store(entity);
        });
    }
    x.Commit();
});

Upvotes: 2

Views: 619

Answers (1)

mythz
mythz

Reputation: 143339

You can pre-fetch a batch of sequence ids then assign them to your models. You can also use StoreAll() which takes advantage of Redis's batch MSET operation so all models get executed/stored in the same operation.

Given this, I would re-write the above with something like:

RedisManager.ExecAs<TEntity>(r => {
   var maxSeqId = r.GetNextSequence(entities.Count);
   var newId = maxSeqId - entities.Count;
   entities.ForEach(x => x.Id = newId++);
   r.StoreAll(entities);
});

Upvotes: 1

Related Questions