Serializers
Serializers are created using AvroSerializer, with settings for how schemas are registered, what schema to use when writing values, and where schema identifiers are written.
The following imports, along with Person and its Codec from the quick example, are assumed on this page.
import cats.effect.{IO, Resource}
import cats.syntax.all.*
import fs2.kafka.ValueSerializer
import fs2.kafka.vulcan.AvroSerializer
import org.http4s.schemaregistry.SchemaRegistryClient
Registering Schemas
By default, the schema of the Codec is registered automatically when serializing, unless it is already registered. We can disable this using withAutoRegisterSchemas(false), in which case the schema is looked up instead, and serialization fails if the schema is not registered. We can then use registerKeySchema or registerValueSchema to register the schema for record keys or values of a topic, or registerSchema to register the schema under a subject.
def registerSchemas(client: SchemaRegistryClient[IO]): IO[Unit] = {
val serializer = AvroSerializer.default(client).withAutoRegisterSchemas(false)
for {
_ <- serializer.registerKeySchema[String]("people")
_ <- serializer.registerValueSchema[Person]("people")
} yield ()
}
Schema Identifiers
Like the Confluent HeaderSchemaIdSerializer, we can use withSchemaIdHeaders(true) to write schema GUIDs in the __key_schema_id and __value_schema_id headers, instead of prefixing values with schema ids. This requires a schema registry supporting schema GUIDs, like Confluent Schema Registry. Deserializers read schema identifiers from these headers when present.
def schemaIdHeadersSerializer(
client: SchemaRegistryClient[IO]
): Resource[IO, ValueSerializer[IO, Person]] =
AvroSerializer.default(client).withSchemaIdHeaders(true).forValue[Person]
Writer Schemas
By default, values are written using the schema of the Codec. Like use.latest.version and use.schema.id for the Confluent serializers, we can use withLatestVersion or withSchemaId to write values using the latest version of the subject, or the schema with an id, in which case schemas are not registered. Serialization fails if values cannot be written using that schema.
def latestVersionSerializer(
client: SchemaRegistryClient[IO]
): Resource[IO, ValueSerializer[IO, Person]] =
AvroSerializer.default(client).withLatestVersion.forValue[Person]