文章目录

  • 前言
  • 6.4 Lua语法入门
  • 6.4.1 初识Lua
  • 6.4.2 Hello World
  • 6.4.3 变量
  • 6.4.3.1 Lua的数据类型
  • 6.4.3.2 声明变量
  • 6.4.4 循环
  • 6.4.5 函数
  • 6.4.6 条件控制
  • 6.5 实现多级缓存
  • 6.5.1 安装和启动OpenResty
  • 6.5.2 实现ajax请求反向代理至OpenResty集群
  • 6.5.2.1 反向代理配置
  • 6.5.2.2 OpenResty集群监听请求


前言

Redis多级缓存系列文章:

Redis从入门到精通(十六)多级缓存(一)Caffeine、JVM进程缓存

6.4 Lua语法入门

要进行业务Nginx编程,就需要用到Lua语言。Lua语言的官网地址是:https://www.lua.org/

redis lua集群环境 redis集群对lua的支持_redis lua集群环境

6.4.1 初识Lua

进入Lua官网,可以看到官方对Lua语言的定义:

Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.
Lua是一种强大、高效、轻量级、可嵌入的脚本语言。它支持过程式编程、面向对象编程、函数式编程、数据驱动编程和数据描述。

Lua是一种轻量小巧的脚本语言,用标准C语言编写并以源代码形式开放, 其设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。

Lua经常嵌入到C语言开发的程序中,例如游戏开发、游戏插件等。Nginx本身也是C语言开发,因此也允许基于Lua做拓展。

6.4.2 Hello World

CentOS7系统默认已经安装了Lua语言环境,可以直接运行Lua代码。

在虚拟机任意目录下,新建一个hello.lua文件,内容如下:

print("Hello World")

执行lua hello.lua命令:

redis lua集群环境 redis集群对lua的支持_lua_02

6.4.3 变量

6.4.3.1 Lua的数据类型

Lua支持的常见数据类型包括:

redis lua集群环境 redis集群对lua的支持_redis_03

Lua提供了一个type()函数来判断一个变量的数据类型:

redis lua集群环境 redis集群对lua的支持_缓存_04

6.4.3.2 声明变量

Lua声明变量时无需指定数据类型,而是用local来声明变量为局部变量:

-- 声明字符串,可以用单引号或双引号
local str = 'hello'
-- 字符串拼接使用 ..
local str2 = 'hello' .. 'hello2'
-- 声明数字
local num = 21
-- 声明布尔类型
local falg = true

Lua的table类型类似于Java中的Map:

-- 声明table,类似Java中的Map
local map = {name = 'Jack', age = 21}
-- 通过key访问table
print(map['name'])
print(map.age)

Lua的table类型也可以作为数组来使用,只是此时的key为数组的角标,且从1开始:

-- 声明数组,key为角标
local arr = {'java', 'python', 'lua'}
-- 访问数组,从角标1开始
print(arr[1])

执行以上程序,结果为:

Jack
21
java

6.4.4 循环

对于table,可以利用for循环来遍历:

  • 遍历数组
local arr = {'java', 'python', 'lua'}
-- for循环遍历数组
for index, value in ipairs(arr) do
    print(index, value)
end

执行以上程序,结果为:

1	java
2	python
3	lua
  • 遍历普通table
local map = {name = 'Jack', age = 21}
-- for循环遍历table
for key, value in pairs(map) do
    print(key, value)
end

执行以上程序,结果为:

name	Jack
age	21

6.4.5 函数

定义函数的语法:

function 函数名(argument1, argument2..., argumentn)
    -- 函数体
    return 返回值
end

例如,定义一个函数用于打印数组:

-- 定义函数:打印数组
function printArr(arr)
    for index, value in ipairs(arr) do
        print(index, value)
    end
end

6.4.6 条件控制

条件控制的语法:

if(布尔表达式)
then
   --语句块
else
   --语句块
end

与Java不同的是,这里的布尔表达式是基于英文单词的,包括:and(逻辑与)、or(逻辑或)、not(逻辑非)。

例如,自定义一个函数,可以打印数组,当参数为nil时,打印错误信息:

function printArr2(arr)
    if not arr
    then
        print('数组为空!')
    else
        for index, value in ipairs(arr) do
            print(index, value)
        end
    end
end

6.5 实现多级缓存

OpenResty是一个基于Nginx的高性能Web平台,用于方便地搭建能够处理超高并发、扩展性极高的动态Web应用、Web服务和动态网关。

其官网地址为:https://openresty.org/cn/

redis lua集群环境 redis集群对lua的支持_redis lua集群环境_05

OpenResty具备下列特点:

  • 具备Nginx的完整功能
  • 基于Lua语言进行扩展,集成了大量精良的 Lua 库、第三方模块
  • 允许使用Lua自定义业务逻辑自定义库

6.5.1 安装和启动OpenResty

  • 1)安装OpenResty依赖开发库
yum install -y pcre-devel openssl-devel gcc --skip-broken

redis lua集群环境 redis集群对lua的支持_redis_06

  • 2)安装OpenResty仓库

安装OpenResty仓库,便于未来安装或更新软件包(通过yum check-update命令):

yum-config-manager --add-repo https://openresty.org/package/centos/openresty.repo

redis lua集群环境 redis集群对lua的支持_redis lua集群环境_07

如果提示命令不存在,则先运行yum install -y yum-utils先安装工具,在重复运行上面的命令。

  • 3)安装OpenResty
yum install -y openresty

redis lua集群环境 redis集群对lua的支持_redis lua集群环境_08

  • 4)安装opm工具

opm是OpenResty的一个管理工具,用于安装第三方的Lua模块:

yum install -y openresty-opm

redis lua集群环境 redis集群对lua的支持_缓存_09

  • 5)OpenResty目录结构

以上命令执行完毕后,OpenResty安装完成,其默认的目录是:/usr/local/openresty

redis lua集群环境 redis集群对lua的支持_lua_10

可以看到,OpenResty安装目录中有一个nginx文件夹,因此可以说OpenResty就是在Nginx的基础上继承了一些Lua模块。

  • 6)配置Nginx环境变量

修改配置文件/etc/profile,在最下面添加以下内容:

export NGINX_HOME=/usr/local/openresty/nginx
export PATH=${NGINX_HOME}/sbin:$PATH

然后执行source /etc/profile命令让配置生效。

  • 7)启动和运行OpenResty

修改Nginx配置文件(由于Nginx默认配置文件注释太多,影响编辑,所以可以将注释部分删掉,只保留需要的部分):

# /usr/local/openresty/nginx/conf/nginx.conf

# user  nobody;
worker_processes  1;
error_log  logs/error.log;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8082;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

OpenResty底层是基于Nginx的,它内部nginx目录和普通的Nginx的目录是一致的,所以启动方式也基本一致:

# 启动nginx(已配置环境变量)
nginx
# 重新加载配置
nginx -s reload
# 停止nginx
nginx -s stop

启动后,在浏览器访问:http://192.168.146.128:8082/,出现以下页面,说明OpenResty安装成功。

redis lua集群环境 redis集群对lua的支持_lua_11

  • 8)OpenResty集群模拟

可以在Nginx配置文件的http块下增加一个server,配置不同的端口,以模拟OpenResty集群:

# /usr/local/openresty/nginx/conf/nginx.conf

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8082;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
    
    server {
        listen       8083;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}

执行nginx -s reload命令重启服务,此时8082端口和8083端口均可访问OpenResty的主页。

6.5.2 实现ajax请求反向代理至OpenResty集群

下面来梳理一下多级缓存的架构,如图:

redis lua集群环境 redis集群对lua的支持_lua_12

如上图所示,在Windows上部署的Nginx用来做反向代理服务,将前端的查询商品信息的ajax请求代理到部署在虚拟机上的OpenResty集群;而OpenResty集群用来编写业务,按照Nginx本地缓存、Redis、Tomcat的顺序依次查询。

6.5.2.1 反向代理配置

修改Windows的反向代理Nginx服务的配置文件,将前端的ajax请求反向代理到OpenResty集群,如图:

redis lua集群环境 redis集群对lua的支持_缓存_13

6.5.2.2 OpenResty集群监听请求

OpenResty的很多功能都依赖于其目录下的Lua库,因此需要在nginx.conf中指定依赖库的目录,并导入依赖:

  • 1)添加对OpenResty的Lua模块的加载

修改/usr/local/openresty/nginx/conf/nginx.conf文件,在其中的http块中,添加下面代码:

#lua 模块
lua_package_path "/usr/local/openresty/lualib/?.lua;;";
#c模块     
lua_package_cpath "/usr/local/openresty/lualib/?.so;;";
  • 2)监听/api/item路径

修改/usr/local/openresty/nginx/conf/nginx.conf文件,在其中的server块中,添加对/api/item路径的监听:

location /api/item {
    # 默认的响应类型
    default_type application/json;
    # 响应结果由lua/item.lua文件来决定
    content_by_lua_file lua/item.lua;
}
  • 3)编写item.lua文件

/usr/local/openresty/nginx目录下创建文件夹lua,并在lua文件夹内创建新文件:item.lua

redis lua集群环境 redis集群对lua的支持_redis_14

编写item.lua文件,暂时先返回假数据

-- /usr/local/openresty/nginx/lua/item.lua

ngx.say('{"id":1,"name":"SALSA AIR","title":"(集群中的)RIMOWA 21寸托运箱拉杆箱 SALSA AIR系列果绿色 820.70.36.4","price":17900,"image":"https://m.360buyimg.com/mobilecms/s720x720_jfs/t6934/364/1195375010/84676/e9f2c55f/597ece38N0ddcbc77.jpg!q70.jpg.webp","category":"拉杆箱","brand":"RIMOWA","spec":"","status":1,"createTime":"2019-04-30T16:00:00.000+00:00","updateTime":"2019-04-30T16:00:00.000+00:00","stock":2999,"sold":31290}')
  • 4)重新加载配置,刷新页面

完整的nginx.conf配置文件内容如下:

# /usr/local/openresty/nginx/conf/nginx.conf
# user  nobody;
worker_processes  1;
error_log  logs/error.log;

events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       8082;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /api/item {
            # 默认的响应类型
        	    default_type application/json;
        	    # 响应结果由lua/item.lua文件来决定
        	    content_by_lua_file lua/item.lua;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    server {
        listen       8083;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        location /api/item {
            # 默认的响应类型
            default_type application/json;
            # 响应结果由lua/item.lua文件来决定
            content_by_lua_file lua/item.lua;
        }

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

    # lua模块
    lua_package_path "/usr/local/openresty/lualib/?.lua;;";
    # c模块     
    lua_package_cpath "/usr/local/openresty/lualib/?.so;;";  
}

执行以下命令重新加载配置文件:

nginx -s reload

浏览器刷新页面:

redis lua集群环境 redis集群对lua的支持_redis_15

可见,页面确实从OpenResty集群拿到了数据。

本节完,下一节继续进行多级缓存的实现。