一,测试环境
$ cat /etc/issue
Ubuntu 18.04.3 LTS n l
$ uname -a
Linux lenky-virtual-machine 5.0.0-27-generic #28~18.04.1-Ubuntu SMP Thu Aug 22 03:00:32 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
二,下载源码
1,下载nginx:
$ wget http://nginx.org/download/nginx-1.17.9.tar.gz
2,下载njs:
$ sudo apt install mercurial
$ hg clone http://hg.nginx.org/njs
三,编译安装
1,准备依赖包
$ sudo apt-get install build-essential
$ sudo apt-get install openssl libssl-dev libpcre3 libpcre3-dev zlib1g-dev
2,三板斧编译
$ sudo mkdir /opt/nginx
$ tar xf nginx-1.17.9.tar.gz
$ cd nginx-1.17.9/
$ sudo ./configure –prefix=/opt/nginx/
执行上面一步不报错,nginx就可以编译了。不过下面加上njs的支持:
$ ls /home/lenky/nginx-dir/njs
$ sudo ./configure –prefix=/opt/nginx/ –add-module=/home/lenky/nginx-dir/njs/nginx
$ sudo make
$ sudo make install
四,运行启动
$ cd /opt/nginx/
$ sudo ./sbin/nginx -c ./conf/nginx.conf
$ cd /tmp/
$ wget 127.0.0.1
$ cat index.html
看到Welcome to nginx!就成功了
五,小试njs
$ cd /opt/nginx/conf
$ sudo cp nginx.conf nginx-njs.conf
$ sudo vi nginx-njs.conf
主要是在http的最上加入如下内容:
... http { js_include hello_world.js; server { listen 8000; location / { js_content hello; } } ...
$ sudo vi hello_world.js
内容如下:
$ cat hello_world.js function hello(r) { r.return(200, "Hello world!"); }
重启nginx:
$ sudo killall nginx
$ cd /opt/nginx
$ sudo ./sbin/nginx -c conf/nginx-njs.conf
$ cd /tmp
$ wget 127.0.0.1:8000
$ cat index.html.1
Hello world!
修改hello_world.js的话,需要重新加载配置:
$ cat hello_world.js
function hello(r) { r.return(200, "Hello njs!"); }
$ sudo /opt/nginx/sbin/nginx -s reload
$ wget -q -O – 127.0.0.1:8000
Hello njs!
六,njs的重要数据
njs代码最重要的就是那个参数r了,所以看一下r到底有哪些属性?
$ cd /opt/nginx/conf $ sudo vi hello_world.js $ sudo cat hello_world.js function print_r(obj) { var str=""; for (var item in obj){ str +=item+":t"+ typeof obj[item]+"n"; } return str; } function hello(r) { r.return(200, print_r(r)); } $ sudo /opt/nginx/sbin/nginx -s reload $ wget -q -O - 127.0.0.1:8000 variables: external subrequest: function status: number log: function args: external requestBody: undefined responseBody: string sendHeader: function finish: function httpVersion: string remoteAddress: string headersOut: external internalRedirect: function parent: undefined send: function method: string uri: string error: function headersIn: external warn: function return: function
有了这些属性字段,就可以做很多业务逻辑处理了
当然njs还提供有对应的全局变量和公共库,具体见这里:http://nginx.org/en/docs/njs/reference.html
目前njs还不太完善,性能也有待考量,但也是一个可选方案。另一个方案当然是openresty了…
网友评论已有0条评论, 我也要评论