redis-py中pipline

来源:互联网 发布:nginx ffmpeg hls 编辑:程序博客网 时间:2024/05/15 15:41
>>> with r.pipeline() as pipe:...     while 1:...         try:...             # put a WATCH on the key that holds our sequence value...             pipe.watch('OUR-SEQUENCE-KEY')...             # after WATCHing, the pipeline is put into immediate execution...             # mode until we tell it to start buffering commands again....             # this allows us to get the current value of our sequence...             current_value = pipe.get('OUR-SEQUENCE-KEY')...             next_value = int(current_value) + 1...             # now we can put the pipeline back into buffered mode with MULTI...             pipe.multi()...             pipe.set('OUR-SEQUENCE-KEY', next_value)...             # and finally, execute the pipeline (the set command)...             pipe.execute()...             # if a WatchError wasn't raised during execution, everything...             # we just did happened atomically....             break...        except WatchError:...             # another client must have changed 'OUR-SEQUENCE-KEY' between...             # the time we started WATCHing it and the pipeline's execution....             # our best bet is to just retry....             continue


防止并发情况下的影响,

采用watch用来监控key是否变化。

watch下的代码是直接运行的,调用multi()后才进入缓冲区,等到execute(),缓冲区的代码才一并执行。

如果其他客户端改变了所监控的key,立马抛error

0 0
原创粉丝点击