说明:
OpenResty是一个Web服务器,使用Lua脚本调用Nginx各种功能,高性能。
一、Centos7下安装OpenResty:
1.添加openresty仓库:
[root@localhost ~]# wget https://openresty.org/package/centos/openresty.repo
[root@localhost ~]# mv openresty.repo /etc/yum.repos.d/
[root@localhost ~]# yum check-update
2.安装openresty:
[root@localhost ~]# yum install -y openresty
3.安装openresty-resty(命令行工具):
[root@localhost ~]# yum install -y openresty-resty
二、使用OpenResty,利用Nginx拦截指定请求路径,交由Lua脚本执行数据同步(nginx本地缓存-redis-mysql):
1.创建usersync.lua脚本文件(/root目录,文件名随意):
[root@localhost ~]# vi usersync.lua
增加如下内容:
ngx.header.content_type="application/json;charset=utf8" --请求数据类型为json
local cjson = require("cjson") --导入cjson,json转换工具
local req_params = ngx.req.get_uri_args() --获取请求参数
local user_no = req_params["user_no"] --获取指定参数的值,如http://...?user_no=值
--1.操作nginx本地缓存
local nginx_cache = ngx.shared.dis_cache; --获取nginx本地缓存操作引用
local user_json = nginx_cache:get(user_no); --操作nginx本地缓存中的数据
if user_json == nil --nginx本地缓存中没数据,查redis
then
--2.操作redis
local resty_redis = require("resty.redis") --导入resty.redis
local redis = resty_redis:new()
redis:set_timeout(2000)
local ip = "192.168.233.128" -redis的IP
local port = 6379 -redis的端口
redis:connect(ip, port) --连接redis
user_json = redis:get(user_no) --操作redis中的数据
if user_json == nil --redis中没数据,查mysql
then
--3.操作mysql
local resty_mysql = require("resty.mysql") --导入resty.mysql
local db = resty_mysql:new()
db:set_timeout(2000)
local mysql_info = { --配置mysql连接信息
host = "192.168.233.128",
port = 3306,
database = "mydb",
user = "root",
password = "root"
}
local result = db:connect(mysql_info) --连接mysql
local sql_str = "select user_no,name from user where user_no = " .. user_no --创建sql语句
result = db:query(sql_strl) --执行sql语句
user_json = cjson.encode(result) --将信息转为json串
redis:set(user_no, user_json) --将数据存入redis中
nginx_cache:set(user_no, user_json, 24 * 60 * 60); --将数据存入nginx本地缓存中
db:close() --关闭mysql连接
else
nginx_cache:set(user_no, user_json, 24 * 60 * 60); --将数据存入nginx本地缓存中
ngx.say(user_json) --返回信息给调用端
redis:close()
end
else
ngx.say(user_json) --返回信息给调用端
end
2.定义Nginx本地缓存和配置拦截路径,并使用自定义Lua脚本处理请求事件(nginx已随openresty自动安装):
(1)修改nginx.conf(cd到/usr/local/openresty/nginx/conf目录):
[root@localhost conf]# vi nginx.conf
修改内容如下:
http {
lua_shared_dict dis_cache 128m; #定义nginx本地缓存
server {
listen 8088; #端口
server_name 192.168.233.128; #IP
location /getUserInfo { //配置拦截此请求路径
content_by_lua_file /root/usersync.lua; //执行此脚本文件
}
...
}
}
3.启动nginx(cd到/usr/local/openresty/nginx/sbin目录):
[root@localhost sbin]# ./nginx
可以访问OpenResty首页:
http://192.168.233.128