首先,感谢您阅读本文,并尝试回答它:)
在GCP (Google Cloud Plateform)上,我有一个数据库存储在云SQL上,
2个云函数,第一个用来对数据库发出请求(这个请求可以有1000多个结果),然后将结果发布到PubSub上,第二个用来做web抓取,这要归功于木偶。
第一个云函数代码:
//[Requirement]
const mysql = require('mysql')
const {SecretManagerServiceClient} = require('@google-cloud/secret-manager')
const ProjectID = process.env.secretID
const SqlPass = `projects/xxx`
const client = new SecretManagerServiceClient()
const {PubSub} = require('@google-cloud/pubsub');
const pubSubClient = new PubSub();
const topicName = "xxxxxx";
//[/Requirement]
exports.LaunchAudit = async () => {
const dbSocketPath = "/cloudsql"
const DB_USER = "xxx"
const DB_PASS = await getSecret()
const DB_NAME = "xxx"
const CLOUD_SQL_CONNECTION_NAME = "xxx"
//[SQL CONNEXION]
let pool = mysql.createPool({
connectionLimit: 1,
socketPath: `${dbSocketPath}/${CLOUD_SQL_CONNECTION_NAME}`,
user: DB_USER,
password: DB_PASS,
connectTimeout: 500,
database: DB_NAME
})
//[/SQL CONNEXION]
//set the request
let sql = `select * from * where *;`
//make the setted request
await pool.query(sql, async (e,results) => {
//if there is an error send it
if(e){
throw e
}
//for each result of the query, log it and publish on PubSub ("Audit-property" topic)
results.forEach(async element => {
console.log(JSON.stringify(element))
await msgPubSub(JSON.stringify(element))
})
})
}
async function msgPubSub(data){
//console.log(data)
const messageBuffer = Buffer.from(data)
try {
const topicPublisher = await pubSubClient.topic(topicName).publish(messageBuffer)
console.log("Message id: " + topicPublisher)
} catch (error) {
console.error(`Error while publishing message: ${error.message}`)
}
}首先,当它工作时,在PubSub主题上发布第一条消息需要很长时间,大约6分钟,为什么会有这种延迟?当我做一个大请求(比如500+ result)时,我得到了一个超时错误:Total timeout of API google.pubsub.v1.Publisher exceeded 600000 milliseconds before any response was received.
我尝试发布一条批处理的消息,为云函数添加一些内存,使用google-gax,但得到了相同的结果。
我使用的是nodejs10。
第二个云函数消息部分代码:
exports.MainAudit = async message => {
const property = Buffer.from(message.data, 'base64').toString()
const pProperty = JSON.parse(property)
console.log(property)
}package.json依赖关系:
"dependencies": {
"@google-cloud/pubsub": "^2.6.0",
"@google-cloud/secret-manager": "^3.2.0",
"google-gax": "^2.9.2",
"mysql": "^2.18.1",
"node-fetch": "^2.6.1"
}日志+时间戳:

发布于 2020-12-02 20:30:35
正如代码所示,您正在为您发布的每条消息创建一个新的publisher实例。这是因为pubSubClient.topic(topicName)创建了一个发布到主题的实例。因此,您要为发送的每条消息支付建立连接的开销。相反,您可能希望一次性创建该对象并重用它:
const pubSubClient = new PubSub();
const topicName = "xxxxxx";
const topicPublisher = pubSubClient.topic(topicName)但是,由于在publish调用和msgPubSub调用中使用了await,因此在开始下一次发布之前,您需要等待每条消息发布,这在应用程序中仍然是低效的。发布/订阅客户端库可以batch messages togetherr以实现更有效的发送,但您需要允许对publish的多个调用处于未完成状态才能利用它。您可能希望在发布返回的promises列表的Promise.all上执行await。
https://stackoverflow.com/questions/65105447
复制相似问题