以下是在 Google App Engine 上运行的 Python Flask 应用程序的一部分:
@app.route('/blabla', methods=['GET'])
def blabla():
# memcache.add('key', None) # this "fixes" it!
memcache_client = memcache.Client()
while True:
value = memcache_client.gets('key')
if value is None: # First time
updated_value = 'Bla'
else:
updated_value = value + ', bla'
if memcache_client.cas('key', updated_value):
return updated_value
从空缓存开始,如果我们向/blabla 发出连续的 GET 请求,我希望请求返回:
Bla
Bla, bla
Bla, bla, bla
.
.
(如果由于某种原因在 .gets() 和 cas() 之间的某个时刻缓存被刷新,那么我希望序列重新启动,没问题.)
但是我们没有得到任何东西,因为 memcache_client.cas() 一直返回 False,所以程序卡在了 while -环形。显然发生这种情况是因为 key 'key' 一开始并不存在。
我知道这一点是因为如果我取消对 memcache.add('key', None) 的注释,它就可以正常工作,因为那时 key 就存在并且 .cas() 很高兴并返回 True。但是如果就在 .add() 和 .gets() 之间,一些其他进程要刷新缓存,我们会回到我们开始的地方,一个丢失的键,.cas() 将无限期返回返回 False。所以这不是一个好的解决方案。
如果开头缺少 key ,为什么 .cas() 不起作用?或者至少,为什么 .cas() 不接受 initial_value= 参数,就像它的兄弟 decr() 一样?这是错误还是功能?除了 Guido van Rossum 在他的 single blog post on the matter 中提到它之外,我无法在任何地方找到正确的记录。 —引用 assert 他说 .gets() 不返回 None,他说:
Aside 2: The assert is kind of naive; in practice you'll have to somehow deal with counter initialization.
Dank je wel Guido——有人知道怎么做吗?
请您参考如下方法:
好的,我明白了。
@app.route('/blabla', methods=['GET'])
def blabla():
memcache_client = memcache.Client()
while True:
if memcache.add('key', 'Bla'):
# That's all folks!
return 'Bla'
# add() failed => the key must already exist, we have to compare-and-set.
value = memcache_client.gets(key_name)
if value is None:
# At the time add() failed the key existed, but now gets() is returning None,
# so somebody must have deleted the cache entry in between.
# Let's start from scratch.
continue
updated_value = value + ', bla'
if memcache_client.cas(key_name, updated_value):
return updated_value
else:
continue
它比我希望的要复杂,但它确实有效。
最后的 else: continue 是多余的,但我写它是为了明确表示我们将继续尝试直到成功。
尽管在实践中您将不得不以某种方式处理在多次重试后放弃的问题。
