如何将Expire传递给NRedisStack中的Json键?

问题描述 投票:0回答:1

如何将 Expire 传递给 Json Redis 中的某个键?

我有以下代码,但似乎没有没有构造函数采用过期值

 TimeSpan expiration = TimeSpan.FromDays(1);

 var json = _redis.JSON();

 await json.SetAsync($"exampleKey", "$", exampleList, expiration);

我需要替代

StringSetAsync("Key1", "Value1", new TimeSpan(0, 0, 30))

我尝试通过

_db.KeyExpire()
设置 Expire,但是 transaction 不允许我使用 Json。所以我无法设置 Json,并在一个事务中设置 _db.KeyExpire() :/

json .net-core redis stackexchange.redis
1个回答
0
投票

与 SET 命令(StackExchange.Redis 中的 StringSet)不同,JSON.SET 命令没有定义键过期的 EX 或 PX 参数。因此 NRedisStack 的 json.Set 命令没有这样的参数。

正如您提到的,解决方案是在 json.Set 之后发送单独的 Expire 命令,您可以使用 Pipeline 或 Transaction 来完成:

管道:

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

交易:

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

我检查了附加的代码,它按预期对我有用。 如果您仍然遇到问题,欢迎您分享更多详细信息,例如您使用的 NRedisStack 和 Redis 版本,以及不适合您的代码。

© www.soinside.com 2019 - 2024. All rights reserved.