java解析kafkaavro_如何使用Spring Kafka读取合并模式注册的AVRO消息?

下面的代码可以读取来自客户avro主题的消息。这是我定义的值的AVRO模式。

{

"type": "record",

"namespace": "com.example",

"name": "Customer",

"version": "1",

"fields": [

{ "name": "first_name", "type": "string", "doc": "First Name of Customer" },

{ "name": "last_name", "type": "string", "doc": "Last Name of Customer" },

{ "name": "age", "type": "int", "doc": "Age at the time of registration" },

{ "name": "height", "type": "float", "doc": "Height at the time of registration in cm" },

{ "name": "weight", "type": "float", "doc": "Weight at the time of registration in kg" },

{ "name": "automated_email", "type": "boolean", "default": true, "doc": "Field indicating if the user is enrolled in marketing emails" }

]

}

import com.example.Customer;

import io.confluent.kafka.serializers.KafkaAvroDeserializer;

import org.apache.kafka.clients.consumer.ConsumerRecord;

import org.apache.kafka.clients.consumer.ConsumerRecords;

import org.apache.kafka.clients.consumer.KafkaConsumer;

import org.apache.kafka.common.serialization.StringDeserializer;

import java.util.Calendar;

import java.util.Collections;

import java.util.Properties;

public class KafkaAvroJavaConsumerV1Demo {

public static void main(String[] args) {

Properties properties = new Properties();

// normal consumer

properties.setProperty("bootstrap.servers","127.0.0.1:9092");

properties.put("group.id", "customer-consumer-group-v1");

properties.put("auto.commit.enable", "false");

properties.put("auto.offset.reset", "earliest");

// avro part (deserializer)

properties.setProperty("key.deserializer", StringDeserializer.class.getName());

properties.setProperty("value.deserializer", KafkaAvroDeserializer.class.getName());

properties.setProperty("schema.registry.url", "http://127.0.0.1:8081");

properties.setProperty("specific.avro.reader", "true");

KafkaConsumer kafkaConsumer = new KafkaConsumer<>(properties);

String topic = "customer-avro";

kafkaConsumer.subscribe(Collections.singleton(topic));

System.out.println("Waiting for data...");

while (true){

System.out.println("Polling at " + Calendar.getInstance().getTime().toString());

ConsumerRecords records = kafkaConsumer.poll(1000);

for (ConsumerRecord record : records){

Customer customer = record.value();

System.out.println(customer);

}

kafkaConsumer.commitSync();

}

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值