c# - 使用 ServiceStack 通过 Redis 管理/更新 ASP.NET 中的记录

标签 c# redis servicestack

我有 SQL Server 背景,正在使用 ServiceStack 在 .NET 中尝试 Redis。我并不是说 Redis 会完全替代 SQL Server,但我只是想了解如何使用它的基本概念,以便了解我们可以在哪些方面充分利用它。

我正在努力解决我认为是一个非常基本的问题。我们有一个项目列表,维护在几个不同的数据存储中。为了简单起见,假设该项目的定义是基本的:一个整数 ID 和一个字符串名称。我正在尝试执行以下操作:

  • 存储项目
  • 如果我们只知道项目 ID,则检索项目
  • 如果我们只知道现有项目的 ID,则覆盖该项目
  • 显示该特定类型的所有项目

这是我整理的一些代码:

    public class DocumentRepositoryRedis
    {
        private static string DOCUMENT_ID_KEY_BASE = "document::id::";

        public IQueryable<Document> GetAllDocuments()
        {
            IEnumerable<Document> documentsFromRedis;
            using (var documents = new RedisClient("localhost").As<Document>())
            {
                documentsFromRedis = documents.GetAll();
            }
            return documentsFromRedis.AsQueryable();
        }

        public Document GetDocument(int id)
        {
            Document document = null;
            using (var redisDocuments = new RedisClient("localhost").As<Document>())
            {
                var documentKey = GetKeyByID(document.ID);
                if (documentKey != null)
                    document = redisDocuments.GetValue(documentKey);        
            }
            return document;
        }

        public void SaveDocument(Document document)
        {
            using (var redisDocuments = new RedisClient("localhost").As<Document>())
            {
                var documentKey = GetKeyByID(document.ID);
                redisDocuments.SetEntry(documentKey, document);
            }
        }

        private string GetKeyByID(int id)
        {
            return DOCUMENT_ID_KEY_BASE + id.ToString();
        }
    }

这一切似乎都有效 - 除了 GetAllDocuments 之外。无论我存储了多少文档,都会返回 0 个文档。我做错了什么?

最佳答案

类型化的 Redis 客户端还允许您访问非类型化方法 - 因为 Redis 最终不知道也不关心您的对象类型。因此,当您使用 client.SetEntry() 方法时,它会绕过一些类型化客户端的功能,而仅通过键存储对象。您将需要使用 client.Store 方法,因为它会继续在 Redis 中创建一个 SET,其中包含与您的类型相关的所有对象 ID。这个 SET 很重要,因为 GetAll 方法依靠它来向您返回所有对象。 client.Store 方法会自动推断 ID,因此您需要尝试一下它。

您将更改 GetDocument(int id) 和 SaveDocument(Document document) 方法以使用 client.GetById(string id) 方法,并使用 client.Store(T value) 方法。您将不再需要 GetKeyByID() 方法。我相信您的 Document 对象将需要一个“Id”属性,以便类型化客户端推断您的对象 ID。

关于c# - 使用 ServiceStack 通过 Redis 管理/更新 ASP.NET 中的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16801121/

相关文章:

c# - WinUI ProgressRing 在 WASM 上不显示(Uno 2.4)

c# - 使用 eval 在 gridview 列中进行数据绑定(bind)

javascript - Redis GET 函数返回未定义

c# - OrmLite LocalDate 到 DateTime 转换器未应用于 Sqlite 内存数据库的 Where 子句

servicestack - 使用一个验证器来处理多个请求 DTO?或者单个请求 DTO 的多个验证器?

ServiceStack RequestLogger 仅记录一次服务调用

c# - 如何在没有任何引用的情况下创建类对象的副本?

c# - 在vs2013中,全局asa错误处理不再起作用了吗?

redis - 在 Slave redis db 上写入

java - 绝地武士得到陈旧的数据