You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过编程将Avro Schema转AsyncAPI?是否有相关CLI工具?

Avro Schema 转 AsyncAPI:编程实现与CLI工具方案

一、编程方式转换

转换核心逻辑是:解析Avro Schema,将其适配为AsyncAPI支持的格式(可直接用Avro原生格式,或转为JSON Schema),再填充AsyncAPI文档的必要结构(如info、channels、message等)。

1. JavaScript/TypeScript实现示例

基于avsc(Avro解析库)和@asyncapi/parser(AsyncAPI验证库)完成转换:

步骤1:安装依赖

npm install avsc @asyncapi/parser

步骤2:转换代码

const avro = require('avsc');
const { Parser } = require('@asyncapi/parser');
const fs = require('fs');

// 读取本地Avro Schema文件
const avroSchemaRaw = fs.readFileSync('./user-created.avsc', 'utf8');
const avroSchema = avro.parse(JSON.parse(avroSchemaRaw));

// 方式1:直接使用Avro原生格式作为AsyncAPI消息payload
const asyncApiDoc = {
  asyncapi: '2.6.0',
  info: {
    title: 'User Event Service',
    version: '1.0.0',
    description: 'AsyncAPI文档由Avro Schema生成'
  },
  channels: {
    'user.created': {
      description: '新用户创建时触发的事件',
      publish: {
        message: {
          schemaFormat: 'application/vnd.apache.avro+json;version=1.9.0',
          payload: avroSchema.toJSON() // 输出Avro原生JSON结构
        }
      }
    }
  }
};

// 验证并生成最终AsyncAPI文件
async function generateDoc() {
  try {
    const parser = new Parser();
    const validatedDoc = await parser.parse(asyncApiDoc);
    fs.writeFileSync('./user-service.asyncapi.json', JSON.stringify(validatedDoc.json(), null, 2));
    console.log('AsyncAPI文档生成成功');
  } catch (err) {
    console.error('生成失败:', err);
  }
}

generateDoc();

方式2:转换为JSON Schema(兼容更多AsyncAPI生态工具)

如果需要适配依赖JSON Schema的工具,可先将Avro转为JSON Schema:

// 将Avro Schema转换为JSON Schema
const jsonSchema = avroSchema.toJSONSchema();

// 构建AsyncAPI文档时使用JSON Schema作为payload
const asyncApiDoc = {
  // 保留info、channels等基础结构
  channels: {
    'user.created': {
      publish: {
        message: {
          schemaFormat: 'application/schema+json;version=draft-07',
          payload: jsonSchema
        }
      }
    }
  }
};

二、CLI工具方案

目前没有官方专属CLI,但可通过以下两种方式实现文件转换:

1. 自定义简易CLI

基于上述编程逻辑封装成可直接运行的脚本:

步骤1:创建转换脚本avro-to-asyncapi.js

const avro = require('avsc');
const fs = require('fs');

// 接收命令行参数:输入Avro文件路径、输出AsyncAPI文件路径
const [inputPath, outputPath] = process.argv.slice(2);

if (!inputPath || !outputPath) {
  console.error('使用方式: node avro-to-asyncapi.js <input.avsc> <output.asyncapi.json>');
  process.exit(1);
}

try {
  const avroSchemaRaw = fs.readFileSync(inputPath, 'utf8');
  const avroSchema = avro.parse(JSON.parse(avroSchemaRaw));

  const asyncApiDoc = {
    asyncapi: '2.6.0',
    info: {
      title: 'Avro转换生成的AsyncAPI文档',
      version: '1.0.0'
    },
    channels: {
      'event.generated': {
        publish: {
          message: {
            schemaFormat: 'application/vnd.apache.avro+json;version=1.9.0',
            payload: avroSchema.toJSON()
          }
        }
      }
    }
  };

  fs.writeFileSync(outputPath, JSON.stringify(asyncApiDoc, null, 2));
  console.log(`✅ 转换成功:${inputPath} → ${outputPath}`);
} catch (err) {
  console.error('❌ 转换失败:', err.message);
  process.exit(1);
}

步骤2:运行CLI

node avro-to-asyncapi.js ./input.avsc ./output.asyncapi.json

2. AsyncAPI CLI扩展(进阶)

如果需要更完善的功能(如批量转换、自定义模板),可以结合asyncapi-cli开发自定义插件,但对于简单的文件转换,自定义CLI已足够满足需求。


内容的提问来源于stack exchange,提问作者jabrena

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 10:15:37