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

懵懂的女人 提交于 2021-02-10 07:14:21

问题


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.


回答1:


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();


来源:https://stackoverflow.com/questions/20703579/whats-the-right-way-to-work-with-many-mysql-servers-from-node-js-simultaneously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!