【问题标题】:How do I check the content of a Django cache with Python memcached?如何使用 Python memcached 检查 Django 缓存的内容?
【发布时间】:2012-01-20 17:18:22
【问题描述】:

工具版本:

  • Python 2.6.5
  • Django 1.3.1
  • memcached 1.4.10
  • python-memcached 1.48

Memcached 当前正在运行:

$ ps -ef | grep memcache
nobody    2993     1  0 16:46 ?        00:00:00 /usr/bin/memcached -m 64 -p 11211 -u nobody -l 127.0.0.1

我在我的 Django 项目中使用 memcached 和 python memcached,我在 settings.py 中设置如下:

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

我已经在代码中设置了缓存:

from django.core.cache import cache
cache.set('countries', ['Canada', 'US'])

然后我打开一个 Django shell 来检查缓存的内容:

>>> from django.core.cache import cache
>>> 'countries' in cache
True
>>> import memcache
>>> mc = memcache.Client(['127.0.0.1:11211'], debug=1)
>>> mc.get('countries')
>>> 

当我使用 Django 的缓存时,countries 键存在。但是,当我使用 Python 的 memcache 时,我没有得到任何国家/地区的信息。我在上面做错了什么?

【问题讨论】:

    标签: python django memcached


    【解决方案1】:

    Django 用冒号作为缓存键的前缀。如果这没有帮助,您可以检查 memcached like so

    【讨论】:

    • 作为参考,django 默认不再在其缓存键前面加上冒号。但是,您仍然可以通过使用此处描述的 KEY_PREFIX 配置选项来实现这一点。 bit.ly/1lzFFPi
    • 为什么要缩短Django Cache Key Prefixing URL?
    • 我这样做是因为我认为我的评论空间会用完。 (以后不会做)
    【解决方案2】:

    您可以从以下位置使用 memcached_stats: https://github.com/dlrust/python-memcached-stats

    示例: (我用pylibmc做缓存,不过我觉得你用python-memcached应​​该是一样的)

    import pylibmc
    
    from memcached_stats import MemcachedStats
    mem = MemcachedStats() # connecting to localhost at default memcached port
    
    # print out all your keys
    mem.keys()
    
    # say for example key[0] is 'countries', then to get the value just do
    key = mem.keys()[0]
    
    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=1)
    value = mc.get (key)
    

    memcaced_stats 还有一个命令行界面: python -m memcached_stats

    看看 github repo,因为 README 很清楚。

    【讨论】:

    • 您的代码中有一个错误,您在其中执行 mc.get() .. 什么是 mc...?我假设它来自 pylibmc。 +1 - 寿。 memcached-stats 库很棒。
    • 参见文档sendapatch.se/projects/pylibmc ...典型的客户端实例化...mc = pylibmc.Client(["127.0.0.1"], binary=True,behaviors={"tcp_nodelay": True, "ketama": True})
    【解决方案3】:

    以下脚本转储 memcached 服务器的所有密钥。它使用 Ubuntu 12.04 和 localhost memcached 进行了测试,因此您的里程可能会有所不同。

    #!/usr/bin/env bash
    
    echo 'stats items'  \
    | nc localhost 11211  \
    | grep -oe ':[0-9]*:'  \
    | grep -oe '[0-9]*'  \
    | sort  \
    | uniq  \
    | xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'
    

    它的作用是遍历所有缓存板并打印每个缓存板的 1000 个键。

    【讨论】:

    • 它不会转储 memcached 服务器的所有内容。它只显示现有的键。它已使用 Ubuntu 16.04 进行测试。
    猜你喜欢
    • 2017-05-18
    • 1970-01-01
    • 2015-09-17
    • 2012-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    相关资源
    最近更新 更多