4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでRedisのトランザクションっぽいことをやる

Last updated at Posted at 2015-02-04
test_transaction.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals

import redis
import time
from multiprocessing import Process

r = redis.StrictRedis(host='localhost', port=6379, db=0)
key = "abc"

def do(name, value):
    with r.pipeline() as pipe:
        try:
            pipe.watch(key)
            pipe.multi()

            pipe.set(key, value)
            time.sleep(1)

            pipe.execute()

            print "{} Success!!!".format(name)
        except redis.exceptions.WatchError:
            print "{} WatchError!!!".format(name)

p1 = Process(target=do, args=("p1", 1))
p1.start()
p2 = Process(target=do, args=("p2", 2))
p2.start()

time.sleep(3) # 処理が終わるまで待つ
print r.get(key)

実行結果:
% python test_redis.py
p2 WatchError!!!
p1 Success!!!
1

エラーとなったほうが取り消させるような感じになります。
使いかってがRDBSほどよくないので、ちょっとできるかも的な感じで。

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?