浅尝OpenResty

文章目录

  • 1. 写在前面
  • 2. 下载安装openresty
    • 2.1 下载Openresty
    • 2.2 设置nginx启动
  • 3. 嵌入lua脚本
  • 4. 实践
  • 5. 小结

1. 写在前面

当一个域名中衍生出多个服务的时候,如果想要保持对外服务始终是一个域名,则需要通过nginx反向代理来实现。如果在转发的时候需要对具体的规则进行一些逻辑运算的话,则需要通过嵌入lua脚本来实现,而nginx本身是不支持lua功能的,目前可以通过:

  1. nginx + lua module来实现
  2. Openresty来实现

我这里尝试使用Openresty来实现lua脚本嵌入逻辑实现nginx的请求转发。

2. 下载安装openresty

2.1 下载Openresty

下载可以按照官方文档的步骤进行具体的下载:Openresty下载 - 使用虚拟机Centos的话可以直接参照:Openresty-Centos

# add the yum repo:
wget https://openresty.org/package/centos/openresty.repo
sudo mv openresty.repo /etc/yum.repos.d/openresty.repo

# update the yum index:
sudo yum check-update

# install openresty
sudo yum install -y openresty

完成上面三步就完成了openresty的安装了,此时进入到默认安装路径/usr/local/openresty/bin/可以直接使用./openresty直接启动。

2.2 设置nginx启动

使用openresty启动多少了我们平常使用的nginx有点差异,所以可以通过导入nginx启动的程序到PATH中实现nginx启动。

PATH=/usr/local/openresty/nginx/sbin:$PATH
export PATH

完成之后,就可以直接使用nginx启动了。此时访问localhost可以直接看到openresty的页面。

3. 嵌入lua脚本

我们需要修改/usr/local/openresty/nginx/conf路径下的nginx.conf文件来实现。

server {
        listen       8088;
				server_name  localhost;
        location / {
			    access_by_lua_block {
						percent = 50
						if math.random(0,100) > percent then
							return ngx.exec("@8080")
						else
							return ngx.exec("@9090")
						end
					}
				}
        
		    location @8080 {
					proxy_pass http://127.0.0.1:8080;
					add_header Redirect true;
			  }
		
			location @9090 {
				proxy_pass http://127.0.0.1:9090;
				add_header Redirect true;
			}
}

上面的lua命令是openresty的lua-nginx-module所支持的,这个命令的含义如下:

Acts as an access phase handler and executes Lua code string specified in { for every request. The Lua code may make API calls and is executed as a new spawned coroutine in an independent global environment (i.e. a sandbox).
充当访问阶段处理器并为每个请求执行{ 简单来说:这个命令就是在请求转发的维护执行,会解析lua,并执行lua中的命令。

lua-nginx-module还支持很多lua的命令,具体可以参照:https://github.com/openresty/lua-nginx-module

上面的lua脚本的含义随机将请求转发到8080和9090,并在response的响应头加上Redirect:true

ngx.exec()这个命令相当于执行API的调用**syntax:** *ngx.exec(uri, args?)*,这里的API可以是具体的路径,也可以是我们配置的location路径,第二个参数为请求的参数。

4. 实践

编写了两个gin的程序,分别监听8080和9090端口。

func main() {
	engine := gin.Default()
	engine.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": "hello world from 8080 port",
		})
	})

	engine.Run(":8080")
}

func main() {
	engine := gin.Default()
	engine.GET("/", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{
			"code": 0,
			"msg":  "success",
			"data": "hello world from 9090 port",
		})
	})

	engine.Run(":9090")
}

按照脚本的逻辑,请求8088的时候,我们的请求会按照50%的概率分别被转发到8080和9090的服务。
浅尝OpenResty_第1张图片
浅尝OpenResty_第2张图片

5. 小结

通过对Openresty的简单尝试,发现nginx+lua的组合可以帮助我们实现更多特定的转发逻辑,本次只是针对概率对不同的API进行转发,通过在请求访问nginx的最尾端实现了lua脚本的按概率转发。除了这一个脚本,Openresty的nginx-lua-module还支持很多诸如init_worker_by_lua、content_by_lua_block、set_by_lua_block等一些十分有用的可以嵌入lua脚本的命令。后续如果再遇到一些更复杂的转发特定逻辑,不妨考虑使用一下其他的命令来帮助我们实现。

你可能感兴趣的:(Linux学习,中间件,学习,openresty,nginx,lua)