Skip to content
This repository was archived by the owner on May 14, 2024. It is now read-only.

Commit c97f1be

Browse files
authored
adding example for cluster-based multithreading
working example of cluster-based multithreading utilizing connectionRouter override.
1 parent 91cac2f commit c97f1be

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

examples/cluster-threading.js

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
const cluster = require('cluster');
2+
const ldap = require('ldapjs');
3+
const os = require('os');
4+
5+
const threads = [];
6+
threads.getNext = function () {
7+
return (Math.floor(Math.random() * this.length));
8+
};
9+
10+
const serverOptions = {
11+
connectionRouter: (socket) => {
12+
socket.pause();
13+
console.log('ldapjs client requesting connection');
14+
let routeTo = threads.getNext();
15+
threads[routeTo].send({ type: 'connection' }, socket);
16+
}
17+
};
18+
19+
const server = ldap.createServer(serverOptions);
20+
21+
if (cluster.isMaster) {
22+
for (let i = 0; i < os.cpus().length; i++) {
23+
let thread = cluster.fork({
24+
'id': i
25+
});
26+
thread.id = i;
27+
thread.on('message', function (msg) {
28+
29+
});
30+
threads.push(thread);
31+
}
32+
33+
server.listen(1389, function () {
34+
console.log('ldapjs listening at ' + server.url);
35+
});
36+
} else {
37+
let threadId = process.env.id;
38+
serverOptions.connectionRouter = (connection) => {
39+
console.log('should not be hit');
40+
};
41+
42+
process.on('message', (msg, socket) => {
43+
switch (msg.type) {
44+
case 'connection':
45+
server.newConnection(socket);
46+
socket.resume();
47+
console.log('ldapjs client connection accepted on ' + threadId.toString());
48+
}
49+
});
50+
51+
server.search('dc=example', function (req, res, next) {
52+
console.log('ldapjs search initiated on ' + threadId.toString());
53+
var obj = {
54+
dn: req.dn.toString(),
55+
attributes: {
56+
objectclass: ['organization', 'top'],
57+
o: 'example'
58+
}
59+
};
60+
61+
if (req.filter.matches(obj.attributes))
62+
res.send(obj);
63+
64+
res.end();
65+
});
66+
}

0 commit comments

Comments
 (0)