How can I set (override) all items in hash

2019-09-08 08:01发布

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

It must Clear all items in hash before running.

It is opposite of GetAllEntriesFromHash.

1条回答
倾城 Initia
2楼-- · 2019-09-08 08:48

You have a couple options here.

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);

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.

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) 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.

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.

查看更多
登录 后发表回答