使用 PM2 和 Nodejs 在多个进程之间共享的单个用户列表

A single list of users shared between several process using PM2 and Nodejs

让多个进程共享一个用户列表的最佳方法是什么?。这些进程使用 PM2 启动。

进程将有权访问该列表,以便添加、删除和检查用户是否已存在于列表中。

最简单的方法是使用redis(或memocache,甚至mongodb)来存储这些用户列表。

或者你将不得不在你的情况下处理非常复杂的 IPC,因为 pm2 使用节点集群,基于 child_process。

您可以使用像 Redis 这样的 in-memory 数据存储。

Redis 作为一个单独的进程运行并在 TCP 端口(默认为 6379)上处理请求。 Redis 是一个 key-value 数据存储,可供所有节点进程使用。

你可以这样做:

  1. 列表项
  2. 安装redis。 (https://redis.io/)
  3. 为 redis 安装节点客户端:

npm install --save redis

  1. 现在您可以使用redis 来存储您的应用程序状态数据并跨进程共享它。

请参考 this link 代码示例。

我刚刚使用 redis 为最多 1200 个实例的大型网络爬虫系统编写了一个作业跟踪记录器。

好的!让我们开始吧!

首先你需要定义它:

const redis = require("redis");
const client_redis = redis.createClient({
  retry_strategy: function(options) {
    if (options.error && options.error.code === "ECONNREFUSED") {
      // End reconnecting on a specific error and flush all commands with
      // a individual error
      return new Error("The server refused the connection");
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
      // End reconnecting after a specific timeout and flush all commands
      // with a individual error
      return new Error("Retry time exhausted");
    }
    if (options.attempt > 10) {
      // End reconnecting with built in error
      return undefined;
    }
    // reconnect after
    return Math.min(options.attempt * 100, 3000);
  },
});

此功能用于更新和创建日志。

function create_and_update_log(productName2, url2, proc, msg) {
    var data_value = {
        id: 'BESTBUY::DATA_LOG::'+md5(productName2 + url2),
        totalrv: 'WAIT',
        product: productName2,
        url: url2,
        process: proc,
        task: msg,
        timestamp: moment().format('DD/MM/YYYY HH:mm:ss')
    };

    client_redis.set('BESTBUY::DATA_LOG::'+md5(productName2 + url2), JSON.stringify(data_value));
}

此函数查询所有数据

async function get_log_redis() {
    return new Promise(function(resolve, reject) {
        try {
            var logger_data = {
                logger: []
            };
            client_redis.multi()
                .keys('BESTBUY::DATA_LOG::*', function(err, replies) {
                    replies.forEach(function(reply, index) {
                        client_redis.get(reply, function(err, data) {
                            if (!data.includes("Total reviews left: 0")) {
                                logger_data.logger.push(JSON.parse(data));
                            }

                            if (index == replies.length - 1) {
                                resolve(logger_data);
                            }
                        });
                    });

                })
                .exec(function(err, replies) {});
        } catch (err) {
            console.log(err);
        }
    });
}

记得替换:

BESTBUY::DATA_LOG::

...用你想定义的。

最后是如何获取属于我的键名以"BESTBUY::DATA_LOG::"

开头的所有日志
            var log_obj_data = "";
            (async () => {
                var log_obj_data = await get_log_redis();

                response.writeHead(200, {
                    "Content-Type": "application/json"
                });
                response.end(JSON.stringify(log_obj_data));
            })();