openresty 缓存后端数据,



openresty 缓存后端数据

         

           

                                  

缓存后端数据

         

请求流程

客户端发起请求流程,如果命中openresty缓存,直接返回数据;

如果没有命中openresty缓存,就去后端数据库查询;

后端查询返回数据,openresty将数据缓存,并返回给客户端

               

 如果缓存数据量不大,openresty可开启定时任务,每隔一段时间全量更新缓存

          

             

                                  

使用示例

         

创建mysql容器

docker run -it -d --net fixed --ip 172.18.0.61 -p 3306:3306 \
-e MYSQL_ROOT_PASSWORD=123456 --name mysql4 mysql

        

数据库变更:权限、建表、插入数据

mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY '123456';
Query OK, 0 rows affected (0.01 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> create database lihu;
ERROR 1007 (HY000): Can't create database 'lihu'; database exists
mysql> drop database lihu;
Query OK, 1 row affected (0.04 sec)

mysql> create database lihu;
Query OK, 1 row affected (0.01 sec)

mysql> use lihu;
Database changed

mysql> create table test(id int not null primary key auto_increment, name varchar(20));
Query OK, 0 rows affected (0.04 sec)

mysql> insert into test(id, name) values(1, 'gtlx'), (2, 'hzw');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql> select * from test;
+----+------+
| id | name |
+----+------+
|  1 | gtlx |
|  2 | hzw  |
+----+------+
2 rows in set (0.00 sec)

           

nginx.conf

pcre_jit on;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
events {
    worker_connections  1024;
}
 
 
http {
    include       mime.types;
    default_type  application/octet-stream;
 
    client_body_temp_path /var/run/openresty/nginx-client-body;
    proxy_temp_path       /var/run/openresty/nginx-proxy;
    fastcgi_temp_path     /var/run/openresty/nginx-fastcgi;
    uwsgi_temp_path       /var/run/openresty/nginx-uwsgi;
    scgi_temp_path        /var/run/openresty/nginx-scgi;
 
    sendfile        on;
 
    keepalive_timeout  65;
 
    include /etc/nginx/conf.d/*.conf;
 
    #设置共享缓存
    lua_shared_dict test 10m;
}

           

default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /usr/local/openresty/nginx/html;
        index  index.html index.htm;
    }

    location /test {
        content_by_lua_block {
            local cache = ngx.shared.test;
            local cjson = require 'cjson';

            local mysql = require 'resty.mysql';
            local db, err = mysql:new();
            if not db then 
                ngx.say("mysql创建失败", err);
            end

            db:set_timeout(1000);
            local res, err, errcode, sqlstate = db:connect({
                host = "172.18.0.61", port = 3306, database = "lihu",
                user = "root", password = "123456"
            });
            if not res then
                ngx.say("连接出错", err, errcode, sqlstate);
            end

            local function fetch_data(id)
                local res, err, errcode, sqlstate = db:query(
                          "select * from test where id ="..id
                       );

                if not res then
                     ngx.say("数据查询失败", err);
                     return nil;
                end

                if #res == 0 then
                    ngx.say("后端没有查询到数据");
                    return nil;
                end

                ngx.say("查询结果 ==> ");
                ngx.say(type(res));
                ngx.say(cjson.encode(res));
                for key,value in pairs(res) do
                    ngx.say(key, " ==> ", cjson.encode(value))
                end

                ngx.say("\n后端返回数据 ==> ",res[1].name); 
                return res[1].name;
            end

            local id = ngx.var.arg_id;
            local value, err = cache:get(id);
            if not value then
                value = fetch_data(id);
                cache:set(id, value);
            end

            ngx.say("请求的数据: ",id, " ==> ", value);
        }
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/openresty/nginx/html;
    }

}

          

创建openresty容器

docker run -it -d --net fixed --ip 172.18.0.101 -p 8001:80 \
-v /Users/huli/lua/openresty/cache/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf \
-v /Users/huli/lua/openresty/cache/default.conf:/etc/nginx/conf.d/default.conf \
--name open-cache lihu12344/openresty

            

使用测试

# 后端查询到数据
huli@hudeMacBook-Pro cache % curl --location --request GET 'localhost:8001/test?id=1'
查询结果 ==> 
table
[{"name":"gtlx","id":1}]
1 ==> {"name":"gtlx","id":1}

后端返回数据 ==> gtlx
请求的数据: 1 ==> gtlx

# 后端查询到数据
huli@hudeMacBook-Pro cache % curl --location --request GET 'localhost:8001/test?id=2'
查询结果 ==> 
table
[{"name":"hzw","id":2}]
1 ==> {"name":"hzw","id":2}

后端返回数据 ==> hzw
请求的数据: 2 ==> hzw


# 后端没有查询到数据
huli@hudeMacBook-Pro cache % curl --location --request GET 'localhost:8001/test?id=3'
后端没有查询到数据
请求的数据: 3 ==> nil

# 后端没有查询到数据
huli@hudeMacBook-Pro cache % curl --location --request GET 'localhost:8001/test?id=4'
后端没有查询到数据
请求的数据: 4 ==> nil

                 

                     

相关内容