Last active
December 18, 2015 00:29
-
-
Save seckcoder/5697196 to your computer and use it in GitHub Desktop.
redis transaction
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import redis | |
client = redis.StrictRedis() | |
client.flushdb() | |
def incr(pipe): | |
value = pipe.get('key') | |
value = int(value) + 1 | |
pipe.multi() | |
pipe.set('key', value) | |
def aincr(pipe): | |
value = pipe.get('key') | |
value = int(value) + 1 | |
pipe.multi() | |
pipe.set('akey', value) | |
def randmove(pipe): | |
"""randomly move a member between redis set""" | |
value = pipe.srandmember("skey") | |
pipe.multi() | |
pipe.sadd("askey", value) | |
pipe.srem("skey", value) | |
def randmove_wrongway(pipe): | |
value = pipe.spop("skey") # error! as we are watching skey, we can't modify it. | |
pipe.multi() | |
pipe.sadd("askey", value) | |
client.set("key", 2) | |
client.transaction(aincr, "key") | |
print client.get("akey"), client.get("key") | |
client.sadd("skey", 2, 3, 4) | |
client.transaction(randmove, "skey") | |
print client.smembers("skey"), client.smembers("askey") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment