SETNX with TTL in .NET using StackExchange.Redis

Set key if it does not exist in redis with expiry using StackExchange.Redis

Recently I needed to set redis key if it is not present with specific expiry time to use it as some logical flag.

I knew tat you can use SETNX command for this but did not have any info how to set the expiry time. After some time going through redis documentation and articles found online I found a SET method overload for the redis-cli.> SET "test.key" "test.value" NX EX 900
OK> SET "test.key" "test.value" NX EX 900

You can see that first set returned message OK while the second one returned (nil) meaning that command did not make any change. If I check the value and ttl of the key, it also confirms that there was not change in the second execution because ttl was not reset> mget "test.key"
1) "test.value"> ttl "test.key"
(integer) 881

Regarding the NX and EX flags they have the following meaning and options:

  • NX - Set if does not exist
  • XX - Set if exists
  • NX - Expiry in seconds
  • PX - Expiry in milliseconds

Now, when it comes to using in .NET application, there are many packages that provide you with redis communication, but since on MSDN webiste Microsoft is using StackExchange.Redis package, so I will use the same package for example how to take benefit of previously mentioned redis set command overload.

using StackExchange.Redis;
using System;
namespace ConsoleApp1
    class Program
        static ConnectionMultiplexer redisConnection = ConnectionMultiplexer.Connect("");
        static IDatabase db = redisConnection.GetDatabase(0);
        static void Main(string[] args)
           bool inserted =  db.StringSet("test.key", "test.value", TimeSpan.FromSeconds(900), When.NotExists, CommandFlags.None);





Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.

About the author


Dejan is a passionate Software Architect/Developer. He is highly experienced in .NET programming platform includion ASP.NET MVC and WebApi. He likes working on new technologies and exciting challenging projects

CONNECT WITH DEJAN  Loginlinkedin Logintwitter Logingoogleplus Logingoogleplus


read more


read more

Umbraco CMS

read more


read more

Comments for this article