【问题标题】:ServiceStack Redis latest list by dateServiceStack Redis 最新列表(按日期)
【发布时间】:2015-07-20 04:16:46
【问题描述】:

如果我有课

public class Article
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string ShortDesc { get; set; }
    public DataTime UpateDate { get; set; }
}

根据 UpdateDate 从 Redis 缓存中获取用户列表的最佳方法是什么?

我在 Redis 中看到了许多关于最新列表的示例,但他们都认为添加到列表中的最新元素是最新的,而且获取最近条目列表非常容易。

但就我而言,我需要根据更新日期列出列表或最近更新的文章,例如

记者在一大早添加了一篇带有今天日期的文章 (Id 1 ),然后意识到他错过了昨天的新闻 (Id 2),该新闻需要在网站上使用回溯日期。之后,他添加了一篇带有今天日期的新文章(ID 3)

所以我的提要应该列出:

  • 文章 ID 3
  • 文章 ID 1
  • 文章 ID 2

使用 Redis 实现这一目标的最佳方法是什么?

谢谢

【问题讨论】:

    标签: c# model-view-controller redis servicestack


    【解决方案1】:

    您可以通过在按日期排序的排序列表中维护 id 的索引来做到这一点。

    例如,存储具有不同修改日期的文章列表,例如:

    var articles = new[]
    {
        new Article { Id = 1, Title = "Article 1", ModifiedDate = new DateTime(2015, 01, 02) },
        new Article { Id = 2, Title = "Article 2", ModifiedDate = new DateTime(2015, 01, 01) },
        new Article { Id = 3, Title = "Article 3", ModifiedDate = new DateTime(2015, 01, 03) },
    };
    

    我们可以将所有文章 POCO 存储在 redis 中,方法是使用类型化的 redis 客户端存储它们,例如:

    var redisArticles = Redis.As<Article>();
    redisArticles.StoreAll(articles);
    

    然后每次存储文章时,还要存储文章 id 和修改日期作为排序值。由于排序值需要是数字或字符串值,我们将使用刻度将日期转换为数字值:

    const string LatestArticlesSet = "urn:Article:modified";
    
    foreach (var article in articles)
    {
        Redis.AddItemToSortedSet(LatestArticlesSet, article.Id.ToString(), article.ModifiedDate.Ticks);
    }
    

    现在要按修改日期获取列表文章,我们可以按日期值按降序(即按最新日期)获取所有文章 ID:

    var articleIds = Redis.GetAllItemsFromSortedSetDesc(LatestArticlesSet);
    

    打印 id 转储:

    articleIds.PrintDump();
    
    [
        3,
        1,
        2
    ]
    

    然后您可以通过返回的 id 获取所有文章:

    var latestArticles = redisArticles.GetByIds(articleIds);
    latestArticles.PrintDump();
    

    【讨论】:

    • 感谢您尝试此解决方案。因此,只需确认此命令 redisArticles.GetByIds(articleIds) 将按 articleIds 中的 ID 顺序返回文章
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多