Skip to content

SETNX with TTL #387

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
vskr opened this issue Oct 18, 2013 · 4 comments
Closed

SETNX with TTL #387

vskr opened this issue Oct 18, 2013 · 4 comments

Comments

@vskr
Copy link

vskr commented Oct 18, 2013

Is it possible to do a atomic SETNX with TTL. I use redis as distributed key value store, and am looking to simulate lock -> update -> release pattern on redis.

Since SETNX doesn't take expiration time, if the thread which obtains lock dies subsequent SETNX's are always false

@andymccurdy
Copy link
Contributor

If you're using Redis server 2.6.12 or greater and redis-py 2.7.4 or greater, you can pass additional arguments to the SET command.

r = redis.StrictRedis(...)
r.set('my-key', 'my-value', nx=True, ex=10)  # 10 second expiration, note you can also use `px` for millisecond resolution

You could also do this with LUA scripting or with a pipeline+watch command.

@duhaime
Copy link

duhaime commented May 13, 2018

In case others want to set up a lock pattern in Redis, redlock-py offers an implementation of the redlock algorithm that the Redis docs recommend for this purpose.

@kingname
Copy link

kingname commented Sep 6, 2019

If you're using Redis server 2.6.12 or greater and redis-py 2.7.4 or greater, you can pass additional arguments to the SET command.

r = redis.StrictRedis(...)
r.set('my-key', 'my-value', nx=True, ex=10)  # 10 second expiration, note you can also use `px` for millisecond resolution

You could also do this with LUA scripting or with a pipeline+watch command.

you can not use r.set with nx=True as the replacement of r.setnx,because r.setnx will return True/False to show if this key exists already, but r.set always return None.

@patrick91
Copy link
Contributor

@kingname I know this is an old issue, but this seems to be working as expected now :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants