2

我来自 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 个文档。我究竟做错了什么?

4

1 回答 1

2

类型化的 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。

于 2013-05-29T01:52:37.967 回答