Skip to content

Commit 59f2e8d

Browse files
committed
lib: add flag to drop connection when running in cluster mode
1 parent ce531af commit 59f2e8d

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed

doc/api/net.md

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -599,12 +599,27 @@ changes:
599599

600600
* {integer}
601601

602-
Set this property to reject connections when the server's connection count gets
603-
high.
602+
When the number of connections reaches the threshold of `server.maxConnections`.
603+
604+
1. Node.js will close the connection if the process is not running in cluster mode.
605+
2. Node.js will send the connection to other worker process by default if the process
606+
is running in cluster mode, you can set `server.dropMaxConnection` to `true` to
607+
close the connection.
604608

605609
It is not recommended to use this option once a socket has been sent to a child
606610
with [`child_process.fork()`][].
607611

612+
### `server.dropMaxConnection`
613+
614+
<!-- YAML
615+
added: REPLACEME
616+
-->
617+
618+
* {boolean}
619+
620+
Set this property to `true` to close the connection when the number of connections
621+
reaches the threshold of `server.maxConnections`. It only works in cluster mode.
622+
608623
### `server.ref()`
609624

610625
<!-- YAML

lib/internal/cluster/child.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ function onconnection(message, handle) {
233233

234234
if (accepted && server[owner_symbol]) {
235235
const self = server[owner_symbol];
236-
if (self.maxConnections != null && self._connections >= self.maxConnections) {
236+
if (self.maxConnections != null &&
237+
self._connections >= self.maxConnections &&
238+
!self.dropMaxConnection) {
237239
accepted = false;
238240
}
239241
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
'use strict';
2+
const common = require('../common');
3+
const cluster = require('cluster');
4+
const http = require('http');
5+
6+
if (cluster.isPrimary) {
7+
cluster.fork();
8+
} else {
9+
const server = http.createServer();
10+
server.maxConnections = 0;
11+
server.dropMaxConnection = true;
12+
// When dropMaxConnection is false, the main process will continue to
13+
// distribute the request to the child process, if true, the child will
14+
// close the connection directly and emit drop event.
15+
server.on('drop', common.mustCall((a) => {
16+
process.exit();
17+
}));
18+
server.listen(common.mustCall(() => {
19+
http.get(`http://localhost:${server.address().port}`).on('error', console.error);
20+
}));
21+
}

0 commit comments

Comments
 (0)