gpt4 book ai didi

c# - Redis key partitioning practices with linked items

转载 作者:可可西里 更新时间:2023-11-01 11:21:43 29 4
gpt4 key购买 nike

我正在为其使用 Redis 数据库和 ServiceStack 客户端。我有一个名为“Post”的类,它有一个属性 GroupId。现在,当我存储此类时, key 是“urn:post:2:groupid:123”。现在,如果我想查找与一个组相关的所有帖子,我需要使用 SearchKeys("urn:*groupid:123") 方法来检索与一个组相关的所有帖子。这是使用 Redis 数据库的最佳实践,还是我应该将我的帖子 key 转换为“urn:groupid:123”post:2”的形式?如果是这样,我该如何实现?

课后:

  public class Post
{
public const string POST_INCREMENT_KEY = "POST_INCREMENT";

public string Id { get; set; }
public string Message { get; set; }
public string GroupId { get; set; }

public void BuildId(long uniqueId)
{
Id = uniqueId + ":groupid:" + GroupId;
}
}

存储帖子的代码:

var post = new Post
{
GroupId = groupId,
Message = Request.Form["message"]
};

post.BuildId(_client.Increment(Post.POST_INCREMENT_KEY, 1));
_client.Store(post);

最佳答案

redis 中的最佳实践是 maintain an index of the relationship你要查询。

在Redis中手动维护一个索引

索引只是一个包含您要维护的相关 ID 的 redis SET,如果您想要“检索与一个组相关的所有帖子”,我将维护以下索引:

const string GroupPostIndex = "idx:group>post:{0}";

因此每次存储帖子时,您还想更新索引,例如:

client.Store(post);
client.AddItemToSet(GroupPostIndex.Fmt(groupId), post.Id);

注意:Redis SET 操作是幂等的,因为将一个项目/id 多次添加到 SET 中总是会导致该项目在 SET 中只出现一次,因此无论何时向集合中添加一个项目总是安全的存储 POST 而无需检查它是否已经存在。

现在,当我想检索组中的所有帖子时,我只需要从 SET 中获取所有 ID:

var postIds = client.GetAllItemsFromSet(GroupPostIndex.Fmt(groupId));

然后获取所有具有这些 ID 的帖子:

var posts = redis.As<Post>().GetByIds(postIds);

使用 ServiceStack.Redis 相关实体 API

上面显示了自己在 Redis 中维护索引所需的内容,但由于这是一个常见的用例,ServiceStack.Redis还提供了一个高级类型化 API,您可以使用它。

它允许您存储相关实体:

client.As<Group>().StoreRelatedEntities(groupId, post);

Note: this also takes care of storing the Post

并通过以下方式检索它们:

var posts = client.As<Group>().GetRelatedEntities<Post>(groupId);

它还提供了其他方便的 API,例如快速找出给定组中有多少帖子:

var postsCount = client.As<Group>().GetRelatedEntitiesCount<Post>(groupId);

并删除组中的 1 个或所有实体:

client.As<Group>().DeleteRelatedEntity<Post>(groupId, postId);
client.As<Group>().DeleteRelatedEntities<Post>(groupId); //all group posts

关于c# - Redis key partitioning practices with linked items,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27314891/

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