How do you pass Expire to a key in Json Redis?
I have following code, but it seems there is no constructor that takes Expire value
TimeSpan expiration = TimeSpan.FromDays(1);
var json = _redis.JSON();
await json.SetAsync($"exampleKey", "$", exampleList, expiration);
I need alternative to StringSetAsync("Key1", "Value1", new TimeSpan(0, 0, 30))
I tried to set Expire via _db.KeyExpire()
, but transaction won't let me work with Json. So I cannot set Json, and set _db.KeyExpire() in one transaction :/
Unlike SET command (StringSet in StackExchange.Redis), JSON.SET command does not have an EX or PX argument that defines the Expire of the key. therefore NRedisStack's json.Set command has no such argument.
The solution is, as you mentioned, to send a separate Expire command after the json.Set, you can do it with Pipeline or Transaction:
Pipeline:
IDatabase db = ConnectionMultiplexer.Connect("localhost").GetDatabase();
var pipeline = new Pipeline(db);
string jsonPerson = JsonSerializer.Serialize(new Person { Name = "tutptbs", Age = 21 });
_ = pipeline.Json.SetAsync("key", "$", jsonPerson);
_ = pipeline.Db.KeyExpireAsync("key", TimeSpan.FromSeconds(10));
await pipeline.ExecuteAsync();
Transaction:
IDatabase db = ConnectionMultiplexer.Connect("localhost").GetDatabase();
var transaction = new Transaction(db);
transaction.Db.ExecuteAsync("FLUSHALL");
string jsonPerson = JsonSerializer.Serialize(new Person { Name = "tutptbs", Age = 21 });
_ = transaction.Json.SetAsync("key", "$", jsonPerson);
_ = transaction.Db.KeyExpireAsync("key", TimeSpan.FromSeconds(10));
await transaction.ExecuteAsync();
I checked the attached code and it works for me as expected. If you still encounter problems, you are welcome to share more details such as the NRedisStack and Redis version you are using, and the code that is not working for you.