简体   繁体   中英

StackExchange.Redis - How to add items to a Redis Set

I'm trying to achieve the following scenarios:

  1. Add 5 items of type T to a new Redis SET
  2. Add 1 item of type T to an existing Redis SET

(i know SETADD doesn't care if the set is existing, but just listing my scenarios for reference)

I can see there is SetAddAsync(RedisKey, RedisValue value) and SetAddAsync(RedisKey, RedisValue[] values) , but i'm not sure how to work with it (and which overload to use?)

When i've used StringSet , i simply serialize T to a byte[] , then use that as the RedisValue param.

But not sure how to do it for sets.

This is what i have:

var items = values.Select(serializer.Serialize).ToArray();
await cache.SetAddAsync(key, items);

where serializer is a class which converts T to a byte[]

It is basically identical to how you would use StringSet . The only difference is that when setting a string , it only makes sense to set one value - but when adding to a set , you might want to add 1 or more elements at a time.

If you're adding one element, just use:

db.SetAdd[Async](key, serializedValue);

If you want to add a larger number of items to the set in one go, then first get the serialized items, for example:

var items = Array.ConvertAll(values, value => (RedisValue)serializer.Serialize(value));

or to tweak your existing code:

var items = values.Select(value => (RedisValue)serializer.Serialize(value)).ToArray();

The important difference here is that I expect your original code is ending up with a byte[][] , where-as you need a RedisValue[] . The (RedisValue) cast in the above should fix that for you.

Then call:

db.SetAdd[Async](key, serializedValues);

This corresponds to the variadic form of SADD .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM