ike*_*504 8 node.js google-cloud-platform google-cloud-pubsub
在 GCP(Google Cloud Platform)上,我有一个存储在云 SQL 上的数据库。
我有两个云功能:
第一个云函数的代码:
//[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}`)
}
}
Run Code Online (Sandbox Code Playgroud)
问题:
首先,当它运行时,在 PubSub 主题上发布第一条消息需要很长时间,大约需要 6 分钟。为什么会出现这种延迟?
其次,当我执行一个大请求(例如 500 多个结果)时,我收到超时错误:
Total timeout of API google.pubsub.v1.Publisher exceeded 600000 milliseconds before any response was received.
Run Code Online (Sandbox Code Playgroud)
我尝试发布批量消息,向云功能添加一些内存,使用 google-gax,但得到了相同的结果。
我正在使用 Node.js v10。
第二个云函数的消息部分代码:
exports.MainAudit = async message => {
const property = Buffer.from(message.data, 'base64').toString()
const pProperty = JSON.parse(property)
console.log(property)
}
Run Code Online (Sandbox Code Playgroud)
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"
}
Run Code Online (Sandbox Code Playgroud)
Kam*_*osn 13
正如现在的代码,您正在为您发布的每条消息创建一个新的发布者实例。这是因为pubSubClient.topic(topicName)创建了一个用于发布到主题的实例。因此,您需要为发送的每条消息支付建立连接的开销。相反,您希望一次性创建该对象并重用它:
const pubSubClient = new PubSub();
const topicName = "xxxxxx";
const topicPublisher = pubSubClient.topic(topicName)
Run Code Online (Sandbox Code Playgroud)
但是,这仍然会导致应用程序效率低下,由于使用了awaitonpublish调用和对 的调用,您需要等待每条消息发布才能开始下一条发布msgPubSub。Pub/Sub 客户端库可以将消息批量处理在一起,以提高发送效率,但您需要允许多个调用publish未完成才能利用它。您需要将其await列入Promise.all从发布返回的承诺列表中。
| 归档时间: |
|
| 查看次数: |
6271 次 |
| 最近记录: |