Ejemplo n.º 1
0
        /// <summary>
        ///     Serialize an instance of type <see cref="T"/> to a byte array in avro format. The serialized
        ///     data is preceeded by a "magic byte" (1 byte) and the id of the schema as registered
        ///     in Confluent's Schema Registry (4 bytes, network byte order). This call may block or throw
        ///     on first use for a particular topic during schema registration.
        /// </summary>
        /// <param name="topic">
        ///     The topic associated wih the data.
        /// </param>
        /// <param name="data">
        ///     The object to serialize.
        /// </param>
        /// <returns>
        ///     <paramref name="data" /> serialized as a byte array.
        /// </returns>
        public byte[] Serialize(string topic, T data)
        {
            if (!topicsRegistered.Contains(topic))
            {
                string subject = IsKey
                    ? SchemaRegistryClient.ConstructKeySubjectName(topic)
                    : SchemaRegistryClient.ConstructValueSubjectName(topic);

                // first usage: register/get schema to check compatibility

                if (AutoRegisterSchema)
                {
                    SchemaId = SchemaRegistryClient.RegisterSchemaAsync(subject, writerSchemaString).Result;
                }
                else
                {
                    SchemaId = SchemaRegistryClient.GetSchemaIdAsync(subject, writerSchemaString).Result;
                }

                topicsRegistered.Add(topic);
            }

            using (var stream = new MemoryStream(InitialBufferSize))
                using (var writer = new BinaryWriter(stream))
                {
                    stream.WriteByte(Constants.MagicByte);

                    writer.Write(IPAddress.HostToNetworkOrder(SchemaId.Value));
                    avroWriter.Write(data, new BinaryEncoder(stream));

                    // TODO: maybe change the ISerializer interface so that this copy isn't necessary.
                    return(stream.ToArray());
                }
        }
        private async Task <string> GetSchemaIdAsync(Schema schema, CancellationToken cancellationToken)
        {
            var schemaProperties = _options.AutoRegisterSchemas
                    ? (await _client.RegisterSchemaAsync(_groupName, schema.Fullname, schema.ToString(), SerializationType.Avro, cancellationToken).ConfigureAwait(false)).Value
                    : await _client.GetSchemaPropertiesAsync(_groupName, schema.Fullname, schema.ToString(), SerializationType.Avro, cancellationToken).ConfigureAwait(false);

            return(schemaProperties.Id);
        }