Is exists check required before calling StringSet method of StrackExchange.Redis

6.6k views Asked by At

I am using the StackExchange.Redis 1.0.450 nuget in C#. I have code like below which checks if a keyexists in redis before adding it -

if (!Cache.KeyExists(fKey))
{
    Cache.StringSet(fKey, Serialize(data));
}

where Cache is Database object

I was reading about the redis SET command here http://redis.io/commands/set and found that SET will overwrite existing key value if it already exists. Using StackExchange.Redis can I safely remove the exist check condition and call just -

Cache.StringSet(fKey, Serialize(data));

Appreciate your response.

2

There are 2 answers

0
Holger Leichsenring On BEST ANSWER

yes, you can savely remove that. We also don't check for existence as that would lead to have two access points to the cache where only one is necessary. This would really slow down cache access.

You may want to consider three other things:

  • you may have to make the set action repeatable in case the redis cache is not available in the moment of access.
  • you may have to make the initialization of the connection repeatable
  • please refer to buffer redis stream how to make (de)serialization of redis cache entries reliable and fast.
0
Marc Gravell On

The default behavior is to simply overwrite, so if that is ok for you: you don't need a check. There is also an optional when parameter that allows you to control this more finely - see the NX etc parameter in redis SET documentation to see what this means in reality. For "equality" checks, you can use a transaction with a constraint.