-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathping-backend.js
68 lines (66 loc) · 1.58 KB
/
ping-backend.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
'use strict';
const assert = require('assert');
const request = require('superagent');
const Balancer = require('..');
const backends = [
{
host: 'www.baidu.com',
ip: '220.181.57.217'
},
{
host: 'www.baidu.com',
ip: '111.13.101.208'
}
];
const balancer = new Balancer(backends);
const ping = (backend) => {
const url = `${backend.protocol || "http"}://${backend.ip}/`;
const check = () => {
return new Promise((resolve) => {
request.get(url).then(() => {
resolve(true);
}, () => {
resolve(false);
});
});
};
const fns = [];
for (let i = 0; i < 5; i++) {
fns.push(check());
}
return new Promise((resolve, reject) => {
Promise.all(fns).then((result) => {
let passCount = 0;
result.forEach((healthy) => {
if (healthy) {
passCount += 1;
}
});
if (passCount >= 3) {
console.info(`The ${backend.ip} is healthy`);
resolve();
} else {
console.info(`The ${backend.ip} is unhealthy`);
reject(new Error('The backend is unhealthy'));
}
}).catch(reject);
});
};
balancer.startHealthCheck({
ping,
});
const plugin = balancer.plugin();
request.get('/')
.use(plugin)
.then((res) => {
console.info(res.text);
assert.equal(res.request.backendServer.ip, backends[0].ip);
assert.equal(res.status, 200);
}).catch(console.error);
request.get('/')
.use(plugin)
.then((res) => {
console.info(res.text);
assert.equal(res.request.backendServer.ip, backends[1].ip);
assert.equal(res.status, 200);
}).catch(console.error);