gpt4 book ai didi

c# - 在 Redis (ServiceStack RedisClient) 中使用事务自动增加 Id

转载 作者:可可西里 更新时间:2023-11-01 11:02:55 27 4
gpt4 key购买 nike

带有 IncrementKey 的 ActionSuccess 回调在事务中不起作用:

public class Article
{
public long Id { get; set; }
public string Name { get; set; }
}

[Test]
public void Can_create_article_with_autoincremental-id()
{
Article a = new Article() { Name = "I Love Writing Test" };
using (var trans = Redis.CreateTransaction())
{
trans.QueueCommand(r => r.IncrementValue("id:article"), id => a.Id = id);
trans.QueueCommand(r => r.Store<Article>(a));

trans.Commit();
}

Assert.That(Redis.Get<Article>("1").Id,Is.Equal("1"));
}

最佳答案

Redis 事务全部同时执行,回调仅在整个事务完成后触发。因此,您不能在同一事务的另一部分中使用回调中的返回值。

如果您只想存储一个带有自动递增 Id 计数器的文章,您可以简单地执行以下操作:

var a = new Article { 
Id = Redis.As<Article>().GetNextSequence(),
Name = "I Love Writing Test"
};
Redis.Store(a);

不需要为此进行交易。要在事务中使用 Redis 中的值,该事务仅在所有值均未更改时才执行,请使用 WATCH命令。请参阅我之前的回答 for an example .

关于c# - 在 Redis (ServiceStack RedisClient) 中使用事务自动增加 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10907878/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com