在下面的测试中,我试图将密钥的过期时间设置为已通过的时间(10秒前)。我需要它能够抛出异常,如果设置过期“失败”。我知道,我可以在设置缓存之前验证过期时间,但在某些情况下,我可能更喜欢避免单独检查。
从我观察到的(一致的)行为来看,第一次总是“成功”(返回true),第二次则按预期(返回false)。
[Test]
public void SetExpirationToPassed()
{
var key = "testKey";
using (var conn = CreateConnection())
{
// Given
var cache = conn.GetDatabase();
cache.HashSet(key, "full", "test", When.NotExists, CommandFlags.PreferMaster);
Thread.Sleep(10 * 1000);
// When
var expiresOn = DateTime.UtcNow.AddSeconds(-10);
var firstResult = cache.KeyExpire(key, expiresOn, CommandFlags.PreferMaster);
var secondResult = cache.KeyExpire(key, expiresOn, CommandFlags.PreferMaster);
var exists = cache.KeyExists(key);
var ttl = cache.KeyTimeToLive(key);
// Then
secondResult.ShouldBe(false);
firstResult.ShouldBe(false);
exists.ShouldBe(false);
ttl.ShouldBe(null);
}
}
private ConnectionMultiplexer CreateConnection()
{
return ConnectionMultiplexer connection =ConnectionMultiplexer.Connect(...);
}
我可能做错什么了吗?
最佳答案
KeyExpire
返回一个布尔值,指示是否可以设置过期时间。当您将到期时间设置为过去时,密钥将不再存在,因此当您第二次尝试设置它时:它将失败。
因此,预期行为应为:
firstResult.ShouldBe(true);
secondResult.ShouldBe(false);
exists.ShouldBe(false);
ttl.ShouldBe(null);
对于一致运行,您可能还希望在每次运行之前删除密钥:
var cache = conn.GetDatabase();
cache.KeyDelete(key);
cache.HashSet(key, "full", "test", When.NotExists);
在上面。
这一点:对我来说,似乎起到了预期的作用。如果你看到了不一样的东西,请准确地说出哪个结果是出乎意料的。
关于redis - 第一次设置到期已经过去的时间返回True,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25113323/