Reputation: 61
In the following code, the mongoClient.connect call (by default) opens a pool of 5 connections. Since Node is single threaded, only one call (either func1 or func2 can be processed at any time (The second call waits till the first completes). So only one of the five connections from the pool is ever used.
Using Nodejs cluster, if we fork multiple instances, each instance opens it's own connection pool (5 connections per instance).
The question is - how does MongoDB connection pool work in the Node environment. How can we test this to demonstrate the use of multiple connections from the same pool at the same time?
mongoClient.connect('mongodb://localhost', function(err, db){
app.get('/func1', function(req, res){
for (var i=0; i<100000; i++){
db.collection('test').insert({a:i});
}
res.end();
});
app.get('/func2', function(req, res){
for (var i=0; i<100000; i++){
db.collection('test').insert({a:i});
}
res.end();
});
});
Upvotes: 6
Views: 1818
Reputation: 311835
insert
is async so the /func1
and /func2
handlers both just queue up 100000 inserts and then return. The connection pool then operates in the background to execute those inserts no more than 5 at a time (1 per connection in the pool).
Upvotes: 1