Dmitry
Dmitry

Reputation: 191

What's the right way to work with many MySQL servers from Node.js simultaneously?

I develop mobile social network. All data stored in MySQL (via shards). Hot data stored in Redis, and there is shards map in Redis too.

Backend = node.js (express)

What is the right way of fast requests to a different MySQL servers within one request to the back-end from mobile client?

Example:

The client requests the server to the user profile with id = 1, which we store on the server mysql-1 shard #1. At the same moment another client requests the server to the user profile with id = 2, which we store on the server mysql-2 shard #2.

Number of mysql servers will grow. And the number of requests to the server will grow too. Initialize a new connection to MySQL on each request to the backend - I think that isn't good idea.

Upvotes: 2

Views: 2341

Answers (1)

jmingov
jmingov

Reputation: 14003

Welcome @Dmitry, one aproach can be using a pool-cluster of connections.

This module https://github.com/felixge/node-mysql, can help you.

// create

var poolCluster = mysql.createPoolCluster();
poolCluster.add(config); // anonymous group
poolCluster.add('MASTER', masterConfig);
poolCluster.add('SLAVE1', slave1Config);
poolCluster.add('SLAVE2', slave2Config);

// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
poolCluster.getConnection(function (err, connection) {});

// Target Group : MASTER, Selector : round-robin
poolCluster.getConnection('MASTER', function (err, connection) {});

// Target Group : SLAVE1-2, Selector : order
// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
poolCluster.on('remove', function (nodeId) {
  console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 
});

poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {});

// of namespace : of(pattern, selector)
poolCluster.of('*').getConnection(function (err, connection) {});

var pool = poolCluster.of('SLAVE*', 'RANDOM');
pool.getConnection(function (err, connection) {});
pool.getConnection(function (err, connection) {});

// destroy
poolCluster.end();

Upvotes: 2

Related Questions