Skip to content

Instantly share code, notes, and snippets.

@mjrusso
Created October 29, 2010 01:03
Show Gist options
  • Save mjrusso/652679 to your computer and use it in GitHub Desktop.
Save mjrusso/652679 to your computer and use it in GitHub Desktop.
Redis transactions demonstration
# Redis transactions demonstration.
# See the following thread on the Redis mailing list for background:
# http://groups.google.com/group/redis-db/browse_thread/thread/8a981b3fd76f8f41
# Output is included in comments below the code.
import redis
def do(r):
r.watch('mykey1')
txn = r.pipeline()
if r.get('mykey1') == 'xx':
txn.set('mykey2', 'yy').incr('mykey3')
else:
txn.set('mykey2', 'zz').decr('mykey3')
txn.execute()
def see(r):
print 'mykey1: %s' % r.get('mykey1')
print 'mykey2: %s' % r.get('mykey2')
print 'mykey3: %s' % r.get('mykey3')
r = redis.Redis()
r.set('mykey1', 'foo')
r.set('mykey2', 'bar')
r.set('mykey3', 5)
do(r)
see(r)
r.set('mykey1', 'xx')
do(r)
see(r)
# >>> import redis
# >>>
# >>> def do(r):
# ... r.watch('mykey1')
# ... txn = r.pipeline()
# ... if r.get('mykey1') == 'xx':
# ... txn.set('mykey2', 'yy').incr('mykey3')
# ... else:
# ... txn.set('mykey2', 'zz').decr('mykey3')
# ... txn.execute()
# ...
# >>> def see(r):
# ... print 'mykey1: %s' % r.get('mykey1')
# ... print 'mykey2: %s' % r.get('mykey2')
# ... print 'mykey3: %s' % r.get('mykey3')
# ...
# >>> r = redis.Redis()
# >>>
# >>> r.set('mykey1', 'foo')
# True
# >>> r.set('mykey2', 'bar')
# True
# >>> r.set('mykey3', 5)
# True
# >>>
# >>> do(r)
# >>> see(r)
# mykey1: foo
# mykey2: zz
# mykey3: 4
# >>>
# >>> r.set('mykey1', 'xx')
# True
# >>> do(r)
# >>> see(r)
# mykey1: xx
# mykey2: yy
# mykey3: 5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment