django缓存优化(三)

This should give you a feel for how this module operates::

    import memcache
    mc = memcache.Client(['127.0.0.1:11211'], debug=0)

    mc.set("some_key", "Some value")
    value = mc.get("some_key")

    mc.set("another_key", 3)
    mc.delete("another_key")

    mc.set("key", "1") # note that the key used for incr/decr must be a string 此处需注意
    mc.incr("key") # 自增increase
    mc.decr("key") # 自减decrease

The standard way to use memcache with a database is like this:

    key = derive_key(obj)
    obj = mc.get(key)
    if not obj:
        obj = backend_api.get(...)
        mc.set(key, obj)

    # we now have obj, and future passes through this code
    # will use the object from the cache.

上面是python memcache 源码中对其使用方法的简单示例。

安装使用:
pip install python-memcached

 

memcache简单介绍:

1、memcached是最快、最有效率的缓存。完全基于内存的缓存框架。

2、memcached是由C语言编写,具有高性能,是一个分布式的对象缓存系统。

Memcached配置

-p <num>    设置端口号(默认: 11211)
-U <num> UDP监听端口 (默认: 11211, 0 时关闭,用户存取小数据) 
-l <ip_addr> 监听地址 (默认:所有都允许,无论内外网或者本机更换IP,有安全隐患,若设置为127.0.0.1就只能本机访问)
-d 独立进程运行
-u <username> 绑定进程的所有者 <username>
-m <num> 允许最大内存用量,单位M (默认: 64 MB)
-P <file> 将PID写入文件<file>,这样可以使得后边进行快速进程终止, 需要与 -d 一起使用
-s <file> 以unix socket方式监听(只允许本地访问),TCP/UDP将会被禁用

 

Memcached存取命令

1、存储命令:
set:不管key存在与否,强制进行set操作;
add:必须在memcached中不存在相应key才能作用;
replace:要求memcached中必须存在相应key才能作用;
append:将数据追加到key对应value值的末尾。(不允许超过限制,用于管理list)
cas(check and set):另一个存储数据的操作,当你最后一次读取该数据后,
没有其它人修改该数据时,才可以写成功。用于解决更新数据时的竞争。
2、获取命令: get:获取一个key的或多个keys的值; gets:带CAS的get命令,会返回带CAS标识(唯一的64位数字)的value。 delete:删除存在的项 incr/decr:自增或自减。只接受正整数。如果key不存在,incr/decr失败。 flush_all:清除memcached中所有项,主要采取将所有数据设置为过期的方式实现,可指定过期时间。

参考链接:

http://memcached.org/
http://code.google.com/p/memcached/wiki/NewStart?tm=6
http://sendapatch.se/projects/pylibmc/
http://libmemcached.org/libMemcached.html

 

posted @ 2018-08-27 00:47  月上秦少  阅读(281)  评论(0编辑  收藏  举报