Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 683
Vishal Thakur Avatar asked Jun 10 '15 13:06

Vishal Thakur


2 Answers

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.
like image 124
Holger Leichsenring Avatar answered Sep 30 '22 18:09

Holger Leichsenring


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.

like image 42
Marc Gravell Avatar answered Sep 30 '22 18:09

Marc Gravell