【问题标题】:How can I set (override) all items in hash如何设置(覆盖)哈希中的所有项目
【发布时间】:2013-10-27 14:42:39
【问题描述】:

我想在哈希中设置所有条目。 (SetAllEntriesToHash)

运行前必须清除hash中的所有项目。

与GetAllEntriesFromHash相反。

【问题讨论】:

    标签: redis servicestack


    【解决方案1】:

    这里有几个选项。

    1) 您可以使用高级 Redis API 让 ServiceStack 为您处理这些问题。

    public class Poco
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
    }
    
    ...
    
    // Client
    var client = new RedisClient("localhost", 6379);
    
    // This will store the object for you in a Redis hash.
    client.StoreAsHash(new Poco { Id = 1, Name = "Test Name", Description = "Test Description" });
    
    // This will fetch it back for you.
    var result = client.GetFromHash<Poco>(1);
    

    这种方法将使您不必直接处理散列细节。 ServiceStack 会为您计算出所有内容,并将您发送的对象自动填充到哈希中。如果您想更新该对象,只需发送一个具有相同 ID 的新对象即可。

    另一方面,您将放弃对数据在 Redis 中的存储方式的控制权,以获得更轻松的编程体验。

    2)您自己处理所有事情。没有预建 SetAllEntriesToHash 函数。

    // Client
    var client = new RedisClient("localhost", 6379);
    
    // Clear all existing keys
    var keysToClear =  new Dictionary<string,string>();
    client.GetHashKeys("xxxxx").ForEach(k => keysToClear.Add(k, ""));
    client.SetRangeInHash("xxxxx", keysToClear);
    
    // Save new key/values.  
    client.SetRangeInHash("xxxxx", new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("1", "value 1"),
        new KeyValuePair<string, string>("2", "value 2"),
        new KeyValuePair<string, string>("3", "value 3"),
    });
    

    或者,删除并重新创建哈希可能更容易。

    我还想提请您注意 RedisNativeClient。它允许您运行直接映射到 http://redis.io/commands 的 Redis 命令。

    【讨论】:

    • client.Hashes[hashId].Clear(); client.Hashes[hashId].AddRange(hash);
    • 是的,这是删除并重新添加。可能是最简单的。
    猜你喜欢
    • 1970-01-01
    • 2019-03-21
    • 2014-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多