I'm trying to achieve the following scenarios:
T
to a new Redis SETT
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.