目录

一、什么是OpenResty

二、OpenResty安装

传统方式安装

Docker方式安装

三、结合lua简单使用

1、输出helloword

2、限流


一、什么是OpenResty

OpenResty是一个基于Nginx与 Lua 的高性能 Web 平台,其内部集成了大量精良的 Lua 库、第三方模块以及大多数的依赖项。用于方便地搭建能够处理超高并发、扩展性极高的动态 Web 应用、Web 服务和动态网关。OpenResty的目标是让你的Web服务直接跑在Nginx服务内部,充分利用Nginx的非阻塞 I/O 模型,不仅仅对 HTTP 客户端请求,甚至于对远程后端诸如 MySQL、PostgreSQL、Memcached 以及 Redis 等都进行一致的高性能响应。由于OpenResty自身内部有nginx,也可以理解为加强后的nginx。

二、OpenResty安装

传统方式安装

1、获取预编译包

wget https://openresty.org/package/centos/openresty.repo

 如果安装过程中报如下错-bash: wget: command not found 先安装wget

yum -y install wget

 2、移动编译包到etc目录

sudo mv openresty.repo /etc/yum.repos.d/

 如果需要更新资源包执行如下命令进行更新

sudo yum check-update

 列出所有openresty仓库里头的软件包

sudo yum --disablerepo="*" --enablerepo="openresty" list available

3、安装软件包,默认安装在/usr/local/openresty目录下

sudo yum install -y openresty

4、 启动nginx

#启动
/usr/local/openresty/nginx/sbin/nginx 
#重启
/usr/local/openresty/nginx/sbin/nginx -s reload
#停止
/usr/local/openresty/nginx/sbin/nginx -s stop

 5、如果看到如下界面安装成功

 6、查看版本信息

openresty -v

Docker方式安装

1、首先需要有docker环境,docker环境安装参考Docker的入门以及简单应用的安装_熟透的蜗牛的博客-CSDN博客

2、获取镜像文件

docker pull openresty/openresty

 3、创建容器并运行

docker run -id --name openresty -p 80:80 openresty/openresty

4、以宿主机挂在方式运行

 a、创建挂载目录

mkdir -p /data/openresty

 b、将容器中的配置复制到宿主机

docker cp openresty:/usr/local/openresty  /data 

c、停止并删除openresty容器 

docker stop openresty  #停止
docker rm openresty    #删除

d、重新启动容器

docker run --name openresty \
--restart always \
--privileged=true \
-d -p 80:80 \
-v /data/openresty/nginx/conf/nginx.conf:/usr/local/openresty/nginx/conf/nginx.conf \
-v /data/openresty/nginx/logs:/usr/local/openresty/nginx/logs \
-v /etc/localtime:/etc/localtime \
openresty/openresty

三、结合lua简单使用

1、输出helloword

a、在宿主机编辑文件 hello.lua

ngx.say("hello world mayikt");

b、将文件拷贝到openresty容器

进入容器创建文件

docker exec -it openresty /bin/bash #进入容器

mkdir -p /root/lua #创建文件

sudo docker cp /data/openresty/lua/hello.lua openresty:/root/lua/hello.lua #拷贝文件到openresty容器

c、修改nginx配置文件如下

# nginx.conf  --  docker-openresty
#
# This file is installed to:
#   `/usr/local/openresty/nginx/conf/nginx.conf`
# and is the file loaded by nginx at startup,
# unless the user specifies otherwise.
#
# It tracks the upstream OpenResty's `nginx.conf`, but removes the `server`
# section and adds this directive:
#     `include /etc/nginx/conf.d/*.conf;`
#
# The `docker-openresty` file `nginx.vh.default.conf` is copied to
# `/etc/nginx/conf.d/default.conf`.  It contains the `server section
# of the upstream `nginx.conf`.
#
# See https://github.com/openresty/docker-openresty/blob/master/README.md#nginx-config-files
#

#user  nobody;
user root root; #建议使用非root用户
worker_processes 1;

# Enables the use of JIT for regular expressions to speed-up their processing.
pcre_jit on;



#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    # Enables or disables the use of underscores in client request header fields.
    # When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.
    # underscores_in_headers off;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

        # Log in JSON Format
        # log_format nginxlog_json escape=json '{ "timestamp": "$time_iso8601", '
        # '"remote_addr": "$remote_addr", '
        #  '"body_bytes_sent": $body_bytes_sent, '
        #  '"request_time": $request_time, '
        #  '"response_status": $status, '
        #  '"request": "$request", '
        #  '"request_method": "$request_method", '
        #  '"host": "$host",'
        #  '"upstream_addr": "$upstream_addr",'
        #  '"http_x_forwarded_for": "$http_x_forwarded_for",'
        #  '"http_referrer": "$http_referer", '
        #  '"http_user_agent": "$http_user_agent", '
        #  '"http_version": "$server_protocol", '
        #  '"nginx_access": true }';
        # access_log /dev/stdout nginxlog_json;

    # See Move default writable paths to a dedicated directory (#119)
    # https://github.com/openresty/docker-openresty/issues/119
    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;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
	
	server {
        listen       80;
        server_name  localhost;
        charset utf-8;
		set $template_root /root/html;
        #access_log  logs/host.access.log  main;
        # 添加
        location /lua {
			default_type 'text/html';
            content_by_lua_file /root/lua/hello.lua; #当访问/lua路径时就会访问到lua脚本
        }

        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }        
    }

    #include /etc/nginx/conf.d/*.conf; #注释掉这句,不然默认加载的是容器内 /etc/nginx/conf.d/*.conf的配置文件

    # Don't reveal OpenResty version to clients.
    # server_tokens off;
}

d、访问    http://ip/lua

 思考:利用上面的特性就可以将我们有些不需要变化的数据预热到服务器中,而减少数据库访问的压力,降低服务器带宽的占用,然后利用lua脚本去维护少量变化的数据。例如商品详情页中的图片,文字描述,页面上的广告位,轮播图等。

2、限流

a、修改nginx.conf如下

# nginx.conf  --  docker-openresty
#
# This file is installed to:
#   `/usr/local/openresty/nginx/conf/nginx.conf`
# and is the file loaded by nginx at startup,
# unless the user specifies otherwise.
#
# It tracks the upstream OpenResty's `nginx.conf`, but removes the `server`
# section and adds this directive:
#     `include /etc/nginx/conf.d/*.conf;`
#
# The `docker-openresty` file `nginx.vh.default.conf` is copied to
# `/etc/nginx/conf.d/default.conf`.  It contains the `server section
# of the upstream `nginx.conf`.
#
# See https://github.com/openresty/docker-openresty/blob/master/README.md#nginx-config-files
#

#user  nobody;
user root root; #建议使用非root用户
worker_processes 1;

# Enables the use of JIT for regular expressions to speed-up their processing.
pcre_jit on;



#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    # Enables or disables the use of underscores in client request header fields.
    # When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.
    # underscores_in_headers off;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

        # Log in JSON Format
        # log_format nginxlog_json escape=json '{ "timestamp": "$time_iso8601", '
        # '"remote_addr": "$remote_addr", '
        #  '"body_bytes_sent": $body_bytes_sent, '
        #  '"request_time": $request_time, '
        #  '"response_status": $status, '
        #  '"request": "$request", '
        #  '"request_method": "$request_method", '
        #  '"host": "$host",'
        #  '"upstream_addr": "$upstream_addr",'
        #  '"http_x_forwarded_for": "$http_x_forwarded_for",'
        #  '"http_referrer": "$http_referer", '
        #  '"http_user_agent": "$http_user_agent", '
        #  '"http_version": "$server_protocol", '
        #  '"nginx_access": true }';
        # access_log /dev/stdout nginxlog_json;

    # See Move default writable paths to a dedicated directory (#119)
    # https://github.com/openresty/docker-openresty/issues/119
    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;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
	
	#限流设置 允许每秒有2个请求,超过将会限流
    limit_req_zone $binary_remote_addr zone=contentRateLimit:1m rate=2r/s;
    #gzip  on;
	
	server {
        listen       80;
        server_name  localhost;
        charset utf-8;
		set $template_root /root/html;
        #access_log  logs/host.access.log  main;
        # 添加
        location /lua {
			default_type 'text/html';
            content_by_lua_file /root/lua/hello.lua; #当访问/lua路径时就会访问到lua脚本
        }
		location /rate {
			#使用限流配置
			default_type 'text/html';
			limit_req zone=contentRateLimit;
			content_by_lua_file /root/lua/hello.lua;
		}
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }        
    }

    #include /etc/nginx/conf.d/*.conf; #注释掉这句,不然默认加载的是容器内 /etc/nginx/conf.d/*.conf的配置文件

    # Don't reveal OpenResty version to clients.
    # server_tokens off;
}

b、重启openresty容器,访问,当快速访问时页面报错,错误码为503

 c、处理突发流量控制

# nginx.conf  --  docker-openresty
#
# This file is installed to:
#   `/usr/local/openresty/nginx/conf/nginx.conf`
# and is the file loaded by nginx at startup,
# unless the user specifies otherwise.
#
# It tracks the upstream OpenResty's `nginx.conf`, but removes the `server`
# section and adds this directive:
#     `include /etc/nginx/conf.d/*.conf;`
#
# The `docker-openresty` file `nginx.vh.default.conf` is copied to
# `/etc/nginx/conf.d/default.conf`.  It contains the `server section
# of the upstream `nginx.conf`.
#
# See https://github.com/openresty/docker-openresty/blob/master/README.md#nginx-config-files
#

#user  nobody;
user root root; #建议使用非root用户
worker_processes 1;

# Enables the use of JIT for regular expressions to speed-up their processing.
pcre_jit on;



#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    # Enables or disables the use of underscores in client request header fields.
    # When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.
    # underscores_in_headers off;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

        # Log in JSON Format
        # log_format nginxlog_json escape=json '{ "timestamp": "$time_iso8601", '
        # '"remote_addr": "$remote_addr", '
        #  '"body_bytes_sent": $body_bytes_sent, '
        #  '"request_time": $request_time, '
        #  '"response_status": $status, '
        #  '"request": "$request", '
        #  '"request_method": "$request_method", '
        #  '"host": "$host",'
        #  '"upstream_addr": "$upstream_addr",'
        #  '"http_x_forwarded_for": "$http_x_forwarded_for",'
        #  '"http_referrer": "$http_referer", '
        #  '"http_user_agent": "$http_user_agent", '
        #  '"http_version": "$server_protocol", '
        #  '"nginx_access": true }';
        # access_log /dev/stdout nginxlog_json;

    # See Move default writable paths to a dedicated directory (#119)
    # https://github.com/openresty/docker-openresty/issues/119
    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;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
	
	#限流设置 允许每秒有2个请求,超过将会限流
    limit_req_zone $binary_remote_addr zone=contentRateLimit:1m rate=2r/s;
    #gzip  on;
	
	server {
        listen       80;
        server_name  localhost;
        charset utf-8;
		set $template_root /root/html;
        #access_log  logs/host.access.log  main;
        # 添加
        location /lua {
			default_type 'text/html';
            content_by_lua_file /root/lua/hello.lua; #当访问/lua路径时就会访问到lua脚本
        }
		location /rate {
			#使用限流配置
			default_type 'text/html';
			#平均每秒允许不超过2个请求,突发不超过5个请求,并且处理突发5个请求的时候,没有延迟,等到完成之后,按照正常的速率处理
			limit_req zone=contentRateLimit burst=5 nodelay;
			content_by_lua_file /root/lua/hello.lua;
		}
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }        
    }

    #include /etc/nginx/conf.d/*.conf; #注释掉这句,不然默认加载的是容器内 /etc/nginx/conf.d/*.conf的配置文件

    # Don't reveal OpenResty version to clients.
    # server_tokens off;
}

d、控制并发连接数

# nginx.conf  --  docker-openresty
#
# This file is installed to:
#   `/usr/local/openresty/nginx/conf/nginx.conf`
# and is the file loaded by nginx at startup,
# unless the user specifies otherwise.
#
# It tracks the upstream OpenResty's `nginx.conf`, but removes the `server`
# section and adds this directive:
#     `include /etc/nginx/conf.d/*.conf;`
#
# The `docker-openresty` file `nginx.vh.default.conf` is copied to
# `/etc/nginx/conf.d/default.conf`.  It contains the `server section
# of the upstream `nginx.conf`.
#
# See https://github.com/openresty/docker-openresty/blob/master/README.md#nginx-config-files
#

#user  nobody;
user root root; #建议使用非root用户
worker_processes 1;

# Enables the use of JIT for regular expressions to speed-up their processing.
pcre_jit on;



#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    # Enables or disables the use of underscores in client request header fields.
    # When the use of underscores is disabled, request header fields whose names contain underscores are marked as invalid and become subject to the ignore_invalid_headers directive.
    # underscores_in_headers off;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

        # Log in JSON Format
        # log_format nginxlog_json escape=json '{ "timestamp": "$time_iso8601", '
        # '"remote_addr": "$remote_addr", '
        #  '"body_bytes_sent": $body_bytes_sent, '
        #  '"request_time": $request_time, '
        #  '"response_status": $status, '
        #  '"request": "$request", '
        #  '"request_method": "$request_method", '
        #  '"host": "$host",'
        #  '"upstream_addr": "$upstream_addr",'
        #  '"http_x_forwarded_for": "$http_x_forwarded_for",'
        #  '"http_referrer": "$http_referer", '
        #  '"http_user_agent": "$http_user_agent", '
        #  '"http_version": "$server_protocol", '
        #  '"nginx_access": true }';
        # access_log /dev/stdout nginxlog_json;

    # See Move default writable paths to a dedicated directory (#119)
    # https://github.com/openresty/docker-openresty/issues/119
    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;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;
	
	#限流设置 允许每秒有2个请求,超过将会限流
    limit_req_zone $binary_remote_addr zone=contentRateLimit:1m rate=2r/s;
	
	#根据IP地址来限制,存储内存大小10M
    limit_conn_zone $binary_remote_addr zone=perip:10m;
	limit_conn_zone $server_name zone=perserver:10m;
    #gzip  on;
	
	server {
        listen       80;
        server_name  localhost;
        charset utf-8;
		set $template_root /root/html;
        #access_log  logs/host.access.log  main;
        # 添加
		
        location /lua {
			default_type 'text/html';
            content_by_lua_file /root/lua/hello.lua; #当访问/lua路径时就会访问到lua脚本
        }
		
		location /rate {
			#使用限流配置
			default_type 'text/html';
			#平均每秒允许不超过2个请求,突发不超过5个请求,并且处理突发5个请求的时候,没有延迟,等到完成之后,按照正常的速率处理
			limit_req zone=contentRateLimit burst=5 nodelay;
			content_by_lua_file /root/lua/hello.lua;
		}
		
		location /rate1{
        limit_conn perip 0;#单个客户端ip与服务器的连接数 ,设置为0然后连接不上
        limit_conn perserver 10; #限制与服务器的总连接数
		default_type 'text/html';
		content_by_lua_file /root/lua/hello.lua;
		}
		
        # redirect server error pages to the static page /50x.html
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }        
    }

    #include /etc/nginx/conf.d/*.conf; #注释掉这句,不然默认加载的是容器内 /etc/nginx/conf.d/*.conf的配置文件

    # Don't reveal OpenResty version to clients.
    # server_tokens off;
}

 

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐