Server module hot update
fibjs
The http server is an independent server program that resides in memory, which means that the service program often needs to be restarted when there is a version update.
Suppose there is the following service program:
web.js
http handlerapp.js
Application entrance
1
2
3
4
5
6// web.js
var _ver = new Date();
module.exports = function (r) {
r.response.write("Hello, new word @ " + _ver);
}
1
2
3
4
5
6
7
8
9// app.js
var http = require("http");
var vm = require("vm");
var coroutine = require("coroutine");
var webServer = require("./web");
var svr = new http.Server(8080, webServer);
svr.start();
In app.js
direct reference web.js
, when each update applications, they both must be restarted app.js
, there is no way you can simultaneously update the code, so that app.js
automatically loads the latest web.js
it?
We can use fibjs's native SandBoxModule to achieve smooth hot update. To app.js
make some changes:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23// app.js
var http = require("http");
var vm = require("vm");
var coroutine = require("coroutine");
// var webServer = require("./web");
function new_web() {
return new vm.SandBox({
mq: require("mq")
}).require("./web.js", __dirname);
}
// 每 1s 重新载入一遍 ./web.js 文件以更新 srv 的 handler
coroutine.start(function() {
while (true) {
coroutine.sleep(1000);
svr.handler = new_web();
}
})
var svr = new http.Server(8080, new_web());
svr.start();
app.js
Start a cycle, every 1s again require
a web.js
content generation security module for svr
remounted handler
. When web.js
the time required to update the content, simply replace the file, you can achieve a smooth update server program.
👉 [ Domain Routing ]