Using Avro with a Quarkus Application + Kafka + Schema Registry (Product Example)
This guide walks you through building a Quarkus application that:
-
Sends and receives Kafka messages
-
Uses Avro for message serialization
-
Integrates with a Schema Registry
-
Works with a custom
Productobject
Prerequisites
You'll need:
-
Java 17+
-
Maven
-
Docker (for Kafka & Schema Registry)
-
Basic understanding of Quarkus, Kafka, and Avro
Architecture Overview
We’ll build a system with:
-
A REST API to send
Productdata to a Kafka topic -
A Kafka consumer that reads
Productmessages -
A REST API to stream consumed products using SSE (Server-Sent Events)
-
Avro used for data serialization
-
Schema stored and retrieved from a Schema Registry
1. Create the Quarkus Project
Generate a project with required extensions:
2. Define the Avro Schema
Create the Avro schema file product.avsc inside src/main/avro:
When you build the app, Quarkus automatically generates the Java class Product.java based on this schema.
3. Implement the Kafka Producer
Create ProductResource.java to expose a REST endpoint that sends product data to Kafka:
4. Kafka Configuration
In src/main/resources/application.properties, add:
If using Confluent Schema Registry, use quarkus-confluent-registry-avro extension instead and replace the apicurio property with:
5. Implement the Kafka Consumer and SSE Streaming
Create a class ConsumedProductResource.java:
6. Kafka Consumer Configuration
Add to application.properties:
7. Running the Application in Dev Mode
Run the application:
Thanks to Dev Services, Kafka and Apicurio Schema Registry are started automatically in dev mode. No extra Docker setup needed.
Test the endpoints:
-
Send a product:
-
View the streamed products:
You’ll see output like:
8. Running in Production (JVM or Native)
In production, you'll need to run Kafka and Schema Registry yourself (e.g., via Docker). Here's a minimal docker-compose.yml:
You will also need to configure these properties:
9. Building the Application
For JVM build:
For native build (requires GraalVM):
10. Summary
You've just built a Quarkus application that:
✅ Defines a Product Avro schema
✅ Generates Java code from .avsc files
✅ Produces and consumes Avro messages using Kafka
✅ Uses Apicurio (or Confluent) Schema Registry
✅ Leverages Quarkus Dev Services for quick setup
✅ Streams data with Server-Sent Events (SSE)
Niciun comentariu:
Trimiteți un comentariu