1.API参考文档地址
https://avro.apache.org/docs/current/api/java/index.html
2.avro数据格式定义
官网说明:https://avro.apache.org/docs/current/spec.html
这里定义一个简单的schema文件user.avsc,注意
,后缀一定是avsc
,其中的内容如下:
{
"namespace": "com.yyj.avro.demo",
"type": "record",
"name": "User",
"fields": [
{"name": "id", "type": "string"},
{"name": "name", "type": ["string", "null"]},
{"name": "age", "type": ["int", "null"]}
]
}
- namespace:定义了根据 schema 文件生成的类的包名
- type:固定写法
- name:生成的类的名称
- fields:定义了生成的类中的属性的名称和类型,其中"type": [“int”, “null”]的意思是,age 这个属性是int类型,但可以为null
基本类型:null、boolean、int、long、float、double、bytes、string
复杂类型:record、enum、array、map、union、fixed
3.设置maven依赖
<dependencies>
<dependency>
<groupId>org.apache.avro</groupId>
<artifactId>avro</artifactId>
<version>1.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.avro</groupId>
<artifactId>avro-maven-plugin</artifactId>
<version>1.8.2</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>schema</goal>
</goals>
<configuration>
<sourceDirectory>${project.basedir}/src/main/resources/</sourceDirectory>
<outputDirectory>${project.basedir}/src/main/java/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>