【问题标题】:What's the recommended way of creating a large no of google pubsub subscribers in nodejs?在 nodejs 中创建大量 google pubsub 订阅者的推荐方法是什么?
【发布时间】:2020-05-19 11:33:01
【问题描述】:

我需要收听大约 40 个订阅(未来几天这个数字会增加)。

如果那时只有一个订阅,我会执行以下操作,

const subName = 'mysubscription'
const pubSubClient = new PubSub()
const startVidsubscription = pubSubClient.subscription(subName)
startVidsubscription.on('message', messageHandler)

const messageHandler = async(message) => {
// do stuff

}

但是,当我有数十个订阅时,我不能这样做。 所以,我正在尝试以下内容:

// the name is the name of each subscription and the variable is the variable name in which I will be holding the subscription object. 
var subscriptionDetails = [
    {'name': 'M10057-sub-cam1Api', 'variable': 'M10057Subscription'},
    {'name': 'M10058-sub-cam1Api', 'variable': 'M10058Subscription'},
    {'name': 'M10059-sub-cam1Api', 'variable': 'M10059Subscription'},
]

for(const subscription of subscriptionDetails){
        var subscription.variable = pubSubClient.subscription(subscription.name)
        subscription.variable.on('message', messageHandler)
    }

但这给了我像Unexpected token, expected ; 这样的错误。

任何人请告诉我在nodejs中收听大量订阅的推荐方法

【问题讨论】:

    标签: node.js google-cloud-platform publish-subscribe google-cloud-pubsub


    【解决方案1】:

    您的一般方法应该有效。您在将订阅对象分配给 subscription.variable 时可能会遇到问题,该对象已被定义为字符串。

    类似下面的方法会起作用:

    const {PubSub} = require('@google-cloud/pubsub');
    
    const pubSubClient = new PubSub();
    const messageHandler = async(message) => {
      // ... handle message ...
    };
    
    var subscriptionDetails = [
      {'name': 'M10057-sub-cam1Api'},
      {'name': 'M10058-sub-cam1Api'},
      {'name': 'M10059-sub-cam1Api'},
    ];
    
    for (const subscription of subscriptionDetails) {
      subscription.variable = pubSubClient.subscription(subscription.name);
      subscription.variable.on('message', messageHandler);
    }
    

    然后您可以使用subscriptionDetails 中的variable 字段引用订阅对象。

    如果您想引用名为“M10057Subscription”的订阅对象,您可以创建订阅对象的映射:

    var subscriptionDetails = [
      {'name': 'M10057-sub-cam1Api', 'variable': 'M10057Subscription'},
      {'name': 'M10058-sub-cam1Api', 'variable': 'M10058Subscription'},
      {'name': 'M10059-sub-cam1Api', 'variable': 'M10059Subscription'},
    ];
    
    var subscriptionObjects = {};
    
    for (const subscription of subscriptionDetails) {
      subscriptionObjects[subscription.variable] = pubSubClient.subscription(subscription.name);
      subscriptionObjects[subscription.variable].on('message', messageHandler);
    }
    
    // subscriptionObjects['M10057Subscription'] is a subscription object
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2021-12-05
      相关资源
      最近更新 更多