我知道有可能通过 NGINX 服务器内部的 JS 脚本处理每个请求。
我知道有 Lua Nginx 模块和 Lua Redis 驱动程序,并且可以在 Lua 中编写脚本并直接从 NGINX 服务器使用 Redis。
但是,我想使用 NGINX 的标准功能,并且我更喜欢用 JS 编写代码。我想知道是否可以在 NJS 中使用一些 session 存储?怎么做?特别是,我想使用 Redis 作为 session 存储。
最佳答案
如果避免自己为 Nginx 编译和安装第三方模块,我想用 njs 和 Redis 构建 session 存储的最佳方法是利用内置的 ngx_http_upstream_module模块并设置类似的东西
http {
[...]
upstream redis {
server unix:/var/run/redis/nginx.sock;
}
[...]
js_path conf.d/js/;
js_import redismiddleware.js;
[...]
server {
[...]
location /redisadapter {
internal;
try_files @dummy @redis;
}
location /request-we-are-tracking-no-1/ {
js_content redismiddleware.processRequestConditional;
}
[...]
location /request-we-are-tracking-no-2/ {
js_content redismiddleware.processRequestUnconditional;
}
[...]
}
和相应的脚本var queryString = require('querystring')
function processRequestConditional (request) {
request.subrequest('/redisadapter', {
method : 'POST',
body : queryString.stringify({
/* data to transfer to Redis */
})
}).then(function (response) {
var reply = {}
/**
* parsing and checking feedback from Redis,
* saving some data from feedback to reply
* object, doing any things as planned,
* running any additional routines et
* cetera
*/
if (/* Redis reply is OK */) {
return reply;
} else {
throw new Error('Because we don`t like you!')
}
}).then(function (data) {
/**
* Making one more subrequest to obtain the content
* the client is waiting for
*/
request.subrequest('/secret-url-with-content').then(
(response) => request.return(response.httpStatus, response.body)
)
}).catch((error) {
/**
* Returning to client with response "There will be
* be no response"
*/
request.return(403, error.message)
})
}
function processRequestUnconditional (request) {
request.subrequest('/redisadapter', {
method : 'POST',
body : queryString.stringify({
/* data to transfer to Redis */
})
}).then(function (response) {
/**
* parsing and checking feedback from Redis,
* doing some things, running some or other
* additional routines depending on reply
*/
})
request.subrequest('/secret-url-with-content').then(
(response) => request.return(response.httpStatus, response.body)
)
}
export default { processRequestConditional, processRequestUnconditional }
简短的摘要/var/run/redis/nginx.sock
/redisadapter
接收来自 njs 脚本的请求,将它们传输到 Redis 并将回复返回给 njs 方法,该方法启动请求序列 当然,我的简短解释在幕后留下了很多细节,但我希望现在基本概念清楚
随时提出其他问题
关于javascript - 带有 session 存储的 NGINX JavaScript 模块(如 Redis),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57464963/