Full Maven Project Template
In this guide, you’ll learn how to:
-
Define an Avro schema for a
Product(fields:name,code,price) -
Read Avro-serialized data (generic or specific)
-
Convert Avro records to JSON via Jackson
-
Use a full Maven project setup to tie it all together
1. Project Structure
Here’s a suggested directory layout:
2. pom.xml
This pom.xml does:
-
Include
avroandavro-compiler -
Use the
avro-maven-pluginto generate Java classes from.avsc -
Include Jackson for JSON serialization
-
Setup compilation and test dependencies
3. Avro Schema: product.avsc
Place this in src/main/avro/product.avsc:
After you build the project, the Avro plugin will produce a generated Java class com.example.avro.Product.
4. Java Source Files
AvroReader.java
AvroToJsonConverter.java
MainApp.java
5. (Optional) Test Example: AvroJsonTest.java
You could put a test to check the conversion:
You’d have to supply a test Avro file in src/test/resources/test-products.avro.
6. How to Build & Run
-
Compile & generate sources:
The Avro plugin will generate Java classes from
product.avscin thetarget/generated-sources/avrodirectory. -
Package into a JAR:
This produces
product-avro-json-1.0-SNAPSHOT.jarintarget/. -
Run the application:
It will print JSON lines corresponding to each record in the Avro file.
7. Explanation & Notes
-
The Avro Maven plugin reads
.avscfiles insrc/main/avroand generates Java classes undertarget/generated-sources/avro. -
In this example, we use generic records via
GenericRecordto read data; this is flexible and schema-driven. -
We use Jackson to convert Avro
GenericRecordto JSON. -
If you prefer specific records (i.e. use the generated
Productclass directly), you can replace generic reading withSpecificDatumReader<Product>and then doobjectMapper.writeValueAsString(productInstance). -
Be careful about null values or optional fields if you extend the schema.
Niciun comentariu:
Trimiteți un comentariu