Skip to content

Commit 39f7a41

Browse files
committed
Add Pipeline support
1 parent 2bf1307 commit 39f7a41

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

src/NRedisStack/Pipeline.cs

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using NRedisStack.RedisStackCommands;
2+
using StackExchange.Redis;
3+
4+
namespace NRedisStack
5+
{
6+
public class Pipeline
7+
{
8+
private readonly IDatabase _db;
9+
private readonly List<SerializedCommand> _commands = new List<SerializedCommand>();
10+
11+
public Pipeline(IDatabase db)
12+
{
13+
_db = db;
14+
}
15+
16+
public void AddCommand(SerializedCommand command)
17+
{
18+
_commands.Add(command);
19+
}
20+
21+
public RedisResult[] Execute()
22+
{
23+
var transaction = _db.CreateTransaction();
24+
var tasks = new List<Task<RedisResult>>();
25+
foreach (var command in _commands)
26+
{
27+
tasks.Add(transaction.ExecuteAsync(command.Command, command.Args));
28+
}
29+
30+
transaction.Execute();
31+
Task.WhenAll(tasks).Wait();
32+
return tasks.Select(x => x.Result).ToArray();
33+
}
34+
35+
public async Task<RedisResult[]> ExecuteAsync()
36+
{
37+
var transaction = _db.CreateTransaction();
38+
var tasks = new List<Task<RedisResult>>();
39+
foreach (var command in _commands)
40+
{
41+
tasks.Add(transaction.ExecuteAsync(command.Command, command.Args));
42+
}
43+
44+
transaction.Execute();
45+
await Task.WhenAll(tasks);
46+
return tasks.Select(x => x.Result).ToArray();
47+
}
48+
49+
}
50+
}

tests/NRedisStack.Tests/Json/JsonTests.cs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,30 @@ public void Dispose()
2020
redisFixture.Redis.GetDatabase().KeyDelete(_testName);
2121
}
2222

23+
[Fact]
24+
public void TestPipeline()
25+
{
26+
var conn = redisFixture.Redis;
27+
var db = conn.GetDatabase();
28+
IJsonCommands json = new JsonCommands(db);
29+
var keys = CreateKeyNames(1);
30+
var pipeline = new Pipeline(db);
31+
pipeline.AddCommand(json.Set(keys[0], "$", new Person { Name = "Shachar", Age = 23 }));
32+
pipeline.AddCommand(json.Get(keys[0]));
33+
pipeline.AddCommand(json.Set(keys[0], "$.Name", "Shachar2"));
34+
pipeline.AddCommand(json.Get(keys[0]));
35+
pipeline.AddCommand(json.Set(keys[0], "$.Age", 24));
36+
pipeline.AddCommand(json.Get(keys[0]));
37+
var results = pipeline.Execute();
38+
Assert.Equal(6, results.Length);
39+
Assert.Equal("OK", results[0].ToString());
40+
Assert.Equal("{\"Name\":\"Shachar\",\"Age\":23}", results[1].ToString());
41+
Assert.Equal("OK", results[2].ToString());
42+
Assert.Equal("{\"Name\":\"Shachar2\",\"Age\":23}", results[3].ToString());
43+
Assert.Equal("OK", results[4].ToString());
44+
Assert.Equal("{\"Name\":\"Shachar2\",\"Age\":24}", results[5].ToString());
45+
}
46+
2347
[Fact]
2448
public void TestSetFromFile()
2549
{

0 commit comments

Comments
 (0)