如何设置(覆盖)哈希中的所有项目 [英] How can I set (override) all items in hash

查看:45
本文介绍了如何设置(覆盖)哈希中的所有项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to set all entries in Hash. (SetAllEntriesToHash)

它必须在运行前清除散列中的所有项目.

It must Clear all items in hash before running.

它与 GetAllEntriesFromHash 相反.

It is opposite of GetAllEntriesFromHash.

推荐答案

这里有几个选项.

1) 您可以通过使用高级 Redis API 让 ServiceStack 为您处理此问题.

1) You could let ServiceStack take care of this for you by using the high level Redis API.

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 的新对象即可.

This approach will disconnect you from having to deal directly with the hashing particulars. ServiceStack will figure out everything for you and stuff the object you send it into a hash automatically. If you want to update that object, just send it a new one with the same ID.

另一方面,为了更轻松的编程体验,您放弃了对数据在 Redis 中存储方式的控制.

The flip-side of this is that you're giving up control of how your data is stored in Redis for an easier programming experience.

2) 您自己处理所有事情.没有预先构建的 SetAllEntriesToHash 函数.

2) You handle all of the stuff yourself. There is no SetAllEntriesToHash function pre-built.

// 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"),
});

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

Alternatively, it may be easier just to delete and recreate the hash.

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

I would also like to draw your attention to RedisNativeClient. It allows you to run Redis commands that directly map to http://redis.io/commands.

这篇关于如何设置(覆盖)哈希中的所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆