【问题标题】:Memcached Compare-And-Set pattern yields wrong resultMemcached Compare-And-Set 模式产生错误的结果
【发布时间】:2013-09-27 12:55:24
【问题描述】:

我正在尝试按照 Guido 的说明实现 memcached 比较和设置模式:

http://neopythonic.blogspot.nl/2011/08/compare-and-set-in-memcache.html

但是,我似乎没有做对,也不知道出了什么问题。下面的文件使用 Django (1.4.5 Final) 和 python-memcache (1.48)。

settings.py

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
        'LOCATION': '127.0.0.1:11211',
    }
}

djangocache.py

#!/usr/bin/env python
from django.core.cache import cache
import multiprocessing.dummy

django_key = "TEST"
cached_key = cache.make_key(django_key).encode("UTF-8")

def add_to_cache(item):
    client = cache._cache
    #client = cache._lib.Client(cache._servers)

    while True:
        items = client.gets(cached_key)
        if client.cas(cached_key, items+(item,)):
            break

if __name__ == "__main__":
    cache.set(django_key, ())

    p = multiprocessing.dummy.Pool(2)
    p.map(add_to_cache, range(10))
    print(len(cache.get(django_key)))

运行它:

mzialla@Q330 ~/test $ DJANGO_SETTINGS_MODULE=settings python djangocache.py
5

它偶尔会输出 6、7 等,就像您在处理竞争条件时所期望的那样。我已经尝试了多个客户端实例化(见评论)。

帮助?

【问题讨论】:

    标签: django memcached python-memcached


    【解决方案1】:

    python-memcached 默认禁用 cas。通过添加启用它

     client.cache_cas = True
    

    到您的代码。

    感谢Nate Thelen,我在提出这个问题后立即发现了谁的评论。

    【讨论】:

      猜你喜欢
      • 2022-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      • 1970-01-01
      相关资源
      最近更新 更多