zoukankan      html  css  js  c++  java
  • Nginx缓存[proxy cache、memcache]

    nginx自带缓存

    nginx自己有单独的进程来对磁盘上的缓存文件进行扫描,在内存中建立缓存索引。并且有管理进程来对缓存进行过期判断,更新等操作

    定义:只能在http段中使用

    proxy_cache_path /dev/shm/nginx/cache levels=1:2 keys_zone=one:10m inactive=5m loader_sleep=1m max_size=200m;

    /dev/shm                #内存系统,这样缓存将更快。

    level                    #一般最多三级,这里指定二级,第一级目录一个字符命名,第二级有两个字符命名。

    keys_zone            #存储在内存中的元数据的大小

    max_size                #存在shm的内容的大小,即缓存的数据的大小

    inactive                 #如果缓存在指定时间内没有被访问,则强制更新

    loader_time            #每隔指定直接更新内存缓存的索引

    使用:一般在前端使用。后端做一个upstream,这样就缓存效果更好

    location / {

    root html;

    index index.html index.htm;

    proxy_pass http://wxl;

    proxy_cache one;                        #使用刚定义的key_zone

    proxy_cache_valid 200 1m;                #成功响应的缓存时间1分钟

    }

    缓存的内容大概是这个样子

    # cat /dev/shm/nginx/cache/8/c5/8f800960e4ca2d295469ee9efa440c58

    KEY: http://wxl/

    HTTP/1.1 200 OK

    Date: Sat, 16 Jan 2016 02:54:16 GMT

    Server: Apache/2.2.15 (Red Hat)

    Last-Modified: Sat, 16 Jan 2016 02:49:51 GMT

    ETag: "68cc-14-5296a92e464c3"

    Accept-Ranges: bytes

    Content-Length: 20

    Connection: close

    Content-Type: text/html; charset=UTF-8

     

    server3.example.com

     

    基于memcache缓存

    对于常用的数据,也可以缓存在memcache中。性能很好,对于一般的场景都是比较好的选择

    安装memcachd服务: yum install memcached

    后面我以Python连接操作memcache,所以顺便安装连接器:yum install python-memcached.noarch

    server {

        listen 80;

    server_name www.wxl-dede.com;

     

        location / {

        root html;

        set $memcached_key "$uri";                

        memcached_pass 127.0.0.1:11211;

        memcached_connect_timeout 5s;

        memcached_read_timeout 5s;

        memcached_send_timeout 5s;

        memcached_buffer_size 32k;

        error_page 404 502 504 = @fallback;

        }

        location @fallback {

        proxy_pass http://wxl;

        }

    }

    一些指令的解释:

    memcached_pass address[:port]/upstream;         #连接memcache

    memcached_connect_timeout time;                #连接超时时间

    memcached_read_timeout 5s;                    #nginx服务器向mc发出两次写请求之间的等待时间,如果在该段时间内没有进行数据传输,连接将关闭

    memcached_read_timeout 5s;        #两次读请求之间

    memcached_buffer_size 32k;            #nginx接收mc数据的缓冲区大小

     

    这里使用一张图片做测试

    >>> f = open("/root/p.jpg")

    >>> f=f.read()

    >>> mc.add('/pic',f)

    访问:http://www.wxl-dede.com/pic

    访问其他连接直接转到其他fallback

    需要注意的是,nginx只是读数据,但是写数据是有后端的程序来完成。nginx有其他的模块来支持nginx在mc中操作数据,比如:memc_nginx和srcache_nginx的解决方案,这里先不讨论。

  • 相关阅读:
    Android应用增量更新
    corner2
    UIProject
    Argo
    flower-recognition
    Android-Chat-Widget
    leanchat-android
    Beautyacticle
    XianBicycle
    完整性约束(章节摘要)
  • 原文地址:https://www.cnblogs.com/wxl-dede/p/5135894.html
Copyright © 2011-2022 走看看