openresty+lua+memcache 实现静态容灾

实现原理

1、正常情况下在openresty上通过srcache和lua随机取样10%的请求 并将请求返回体写入到memcache中
2、当后端异常时从缓存获取数据。实现方法:判断Nginx的upstream response status,将5xx状态码重定向到缓存获取数据
引用模块:https://github.com/openresty/srcache-nginx-module

配置:

     # 设置一个随机数,进行流量采样
     set srcache_v 0;
     access_by_lua_file 'conf/conf.d/luascripts/srcache_random.lua';
     #根据uri设置需要被缓存的路由
     if (uri ~ (/tk_zs/|/pmc/|/pay/|/cloud/|/set/|/ucenters/|/kfpt/)) {
        set srcache_v 2;
     }
     if (request_uri ~ "_=[0-9]{10,13}") {
        setsrcache_v 2;
     }
     set_md5 mem_keyuriargs;
     srcache_store PUT /memcmem_key;
     srcache_store_skip srcache_v;
     srcache_store_statuses 200 301 302;
     srcache_response_cache_control off;
     srcache_methods GET HEAD;
     srcache_ignore_content_encoding on;
     srcache_max_expire 10h;

     error_page 500 = @down_cache;
     error_page 502 = @down_cache;
     error_page 503 = @down_cache;
     error_page 504 = @down_cache;
 location = /memc {
     internal;

     memc_connect_timeout 100ms;
     memc_send_timeout 100ms;
     memc_read_timeout 100ms;
     memc_ignore_client_abort on;

     setmemc_key query_string;
     setmemc_exptime 36000;
     # memcache地址
     memc_pass memcached;
 }
 location @down_cache {
     more_set_headers "down-memcache: HIT";
     access_log  /var/log/nginx/downcache.www.itgod.org.access.log json;
     srcache_fetch GET /memc $mem_key;
 }

lua随机采样脚本

ngx.var.srcache_v = math.random(0,9)
--ngx.log(ngx.ERR, "===============================")
--ngx.log(ngx.ERR, ngx.var.srcache_v)

memcache的upstram

upstream memcached {
     server m-xxxxxx.memcache.rds.aliyuncs.com:11211 weight=5 max_fails=0 fail_timeout=0s;
     keepalive 100;
}
Copyright © 运维知识库 all right reserved,powered by Gitbook文件修订时间: 2023-09-19 10:45:38

results matching ""

    No results matching ""