如何通过Node.js代码完成Event-Arc配置?
使用Node.js配置Google Cloud Event Arc
1. 安装依赖
- 安装Google Cloud Event Arc官方Node.js客户端库:
npm install @google-cloud/eventarc
2. 配置认证
- 生产环境推荐通过环境变量设置服务账号密钥:
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your-service-account-key.json"
- 开发阶段也可在代码中直接加载密钥(不建议生产使用):
const {Eventarc} = require('@google-cloud/eventarc'); const eventarc = new Eventarc({ keyFilename: '/path/to/your-service-account-key.json', projectId: 'your-project-id', location: 'your-region', // 例如 us-central1 });
3. 创建Event Arc触发器
以下示例实现:当指定Cloud Storage Bucket有新对象上传时,触发目标Cloud Function
async function createStorageTrigger() { const trigger = await eventarc.createTrigger({ triggerId: 'storage-upload-trigger', eventFilters: [ { attribute: 'type', value: 'google.cloud.storage.object.v1.finalized', }, { attribute: 'bucket', value: 'your-source-bucket-name', }, ], destination: { cloudFunction: 'projects/your-project-id/locations/your-region/functions/your-target-function', }, serviceAccount: 'your-trigger-sa@your-project-id.iam.gserviceaccount.com', }); console.log(`触发器创建成功:${trigger.name}`); } createStorageTrigger().catch(console.error);
4. 触发器管理操作
- 列出当前项目下所有触发器:
async function listAllTriggers() { const [triggers] = await eventarc.listTriggers(); triggers.forEach(trigger => { console.log(`触发器ID:${trigger.name.split('/').pop()} | 事件类型:${trigger.eventFilters[0].value}`); }); } listAllTriggers().catch(console.error);
- 删除指定触发器:
async function removeTrigger(triggerId) { const triggerPath = `projects/your-project-id/locations/your-region/triggers/${triggerId}`; await eventarc.deleteTrigger(triggerPath); console.log(`触发器 ${triggerId} 已删除`); } removeTrigger('storage-upload-trigger').catch(console.error);
5. 验证配置有效性
- 上传测试文件到目标Storage Bucket,检查目标Cloud Function的执行日志
- 通过Google Cloud Console查看Event Arc的事件流转记录,确认事件是否正常投递
内容的提问来源于stack exchange,提问作者Praveentrans kumar
相关产品推荐
相关产品推荐

