首先,确保您已经正确设置了AWS Lambda函数的权限。在Lambda控制台中,转到“函数代码”部分,选择“函数ID和角色”,然后将GCP Pub/Sub的权限添加到角色中。
确保您已经正确设置了GCP Pub/Sub的访问控制。在GCP控制台中,转到“IAM和管理”部分,选择“服务帐户”,为您的服务帐户添加“Pub/Sub管理员”或“Pub/Sub编辑器”角色。
在AWS Lambda函数中,使用Google Cloud的Pub/Sub客户端库发送消息。这需要安装Google Cloud Pub/Sub客户端库和Google Auth库。示例代码如下:
const {PubSub} = require('@google-cloud/pubsub');
const pubSubClient = new PubSub({projectId: 'YOUR_PROJECT_ID'});
async function publishMessage() {
// Publish message to Pub/Sub topic
const messageId = await pubSubClient.topic('YOUR_TOPIC_NAME').publish(Buffer.from('your message'));
console.log(Message ${messageId} published.
);
}
const fs = require('fs'); const path = require('path'); const credentials = JSON.parse(fs.readFileSync(path.join(__dirname, 'google-cloud-key.json'))); process.env.GOOGLE_APPLICATION_CREDENTIALS = path.join(__dirname, 'google-cloud-key.json');
这些步骤应该可以解决AWS Node.js Lambda函数无法向GCP Pub/Sub发布消息的问题。
上一篇:AWSNode.js编译器出现“Ineffectivemark-compactsnearheaplimitAllocationfailed-JavaScriptheapoutofmemory”错误。