我想在从/写入Kafka的消息中使用Avro。有没有使用Avro二进制编码器对将放入消息队列的数据进行编码/解码的示例?
我更需要Avro部分而不是Kafka部分。或许我应该考虑其他解决方案?基本上,我正在尝试寻找比JSON更高效的空间解决方案。之所以提到Avro,是因为它可以比JSON更紧凑。
我想在从/写入Kafka的消息中使用Avro。有没有使用Avro二进制编码器对将放入消息队列的数据进行编码/解码的示例?
我更需要Avro部分而不是Kafka部分。或许我应该考虑其他解决方案?基本上,我正在尝试寻找比JSON更高效的空间解决方案。之所以提到Avro,是因为它可以比JSON更紧凑。
这是一个基本示例。我还没有尝试在多个分区/主题中使用它。
//生产者代码示例
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.*;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Properties;
public class ProducerTest {
void producer(Schema schema) throws IOException {
Properties props = new Properties();
props.put("metadata.broker.list", "0:9092");
props.put("serializer.class", "kafka.serializer.DefaultEncoder");
props.put("request.required.acks", "1");
ProducerConfig config = new ProducerConfig(props);
Producer<String, byte[]> producer = new Producer<String, byte[]>(config);
GenericRecord payload1 = new GenericData.Record(schema);
//Step2 : Put data in that genericrecord object
payload1.put("desc", "'testdata'");
//payload1.put("name", "अasa");
payload1.put("name", "dbevent1");
payload1.put("id", 111);
System.out.println("Original Message : "+ payload1);
//Step3 : Serialize the object to a bytearray
DatumWriter<GenericRecord>writer = new SpecificDatumWriter<GenericRecord>(schema);
ByteArrayOutputStream out = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
writer.write(payload1, encoder);
encoder.flush();
out.close();
byte[] serializedBytes = out.toByteArray();
System.out.println("Sending message in bytes : " + serializedBytes);
//String serializedHex = Hex.encodeHexString(serializedBytes);
//System.out.println("Serialized Hex String : " + serializedHex);
KeyedMessage<String, byte[]> message = new KeyedMessage<String, byte[]>("page_views", serializedBytes);
producer.send(message);
producer.close();
}
public static void main(String[] args) throws IOException, DecoderException {
ProducerTest test = new ProducerTest();
Schema schema = new Schema.Parser().parse(new File("src/test_schema.avsc"));
test.producer(schema);
}
}
//示例消费者代码
第一部分:消费者组代码:你可以为多个分区/主题拥有多个消费者。
import kafka.consumer.ConsumerConfig;
import kafka.consumer.KafkaStream;
import kafka.javaapi.consumer.ConsumerConnector;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Created by on 9/1/15.
*/
public class ConsumerGroupExample {
private final ConsumerConnector consumer;
private final String topic;
private ExecutorService executor;
public ConsumerGroupExample(String a_zookeeper, String a_groupId, String a_topic){
consumer = kafka.consumer.Consumer.createJavaConsumerConnector(
createConsumerConfig(a_zookeeper, a_groupId));
this.topic = a_topic;
}
private static ConsumerConfig createConsumerConfig(String a_zookeeper, String a_groupId){
Properties props = new Properties();
props.put("zookeeper.connect", a_zookeeper);
props.put("group.id", a_groupId);
props.put("zookeeper.session.timeout.ms", "400");
props.put("zookeeper.sync.time.ms", "200");
props.put("auto.commit.interval.ms", "1000");
return new ConsumerConfig(props);
}
public void shutdown(){
if (consumer!=null) consumer.shutdown();
if (executor!=null) executor.shutdown();
System.out.println("Timed out waiting for consumer threads to shut down, exiting uncleanly");
try{
if(!executor.awaitTermination(5000, TimeUnit.MILLISECONDS)){
}
}catch(InterruptedException e){
System.out.println("Interrupted");
}
}
public void run(int a_numThreads){
//Make a map of topic as key and no. of threads for that topic
Map<String, Integer> topicCountMap = new HashMap<String, Integer>();
topicCountMap.put(topic, new Integer(a_numThreads));
//Create message streams for each topic
Map<String, List<KafkaStream<byte[], byte[]>>> consumerMap = consumer.createMessageStreams(topicCountMap);
List<KafkaStream<byte[], byte[]>> streams = consumerMap.get(topic);
//initialize thread pool
executor = Executors.newFixedThreadPool(a_numThreads);
//start consuming from thread
int threadNumber = 0;
for (final KafkaStream stream : streams) {
executor.submit(new ConsumerTest(stream, threadNumber));
threadNumber++;
}
}
public static void main(String[] args) {
String zooKeeper = args[0];
String groupId = args[1];
String topic = args[2];
int threads = Integer.parseInt(args[3]);
ConsumerGroupExample example = new ConsumerGroupExample(zooKeeper, groupId, topic);
example.run(threads);
try {
Thread.sleep(10000);
} catch (InterruptedException ie) {
}
example.shutdown();
}
}
第二部分:实际消费信息的个体消费者。
import kafka.consumer.ConsumerIterator;
import kafka.consumer.KafkaStream;
import kafka.message.MessageAndMetadata;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.generic.IndexedRecord;
import org.apache.avro.io.DatumReader;
import org.apache.avro.io.Decoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.specific.SpecificDatumReader;
import org.apache.commons.codec.binary.Hex;
import java.io.File;
import java.io.IOException;
public class ConsumerTest implements Runnable{
private KafkaStream m_stream;
private int m_threadNumber;
public ConsumerTest(KafkaStream a_stream, int a_threadNumber) {
m_threadNumber = a_threadNumber;
m_stream = a_stream;
}
public void run(){
ConsumerIterator<byte[], byte[]>it = m_stream.iterator();
while(it.hasNext())
{
try {
//System.out.println("Encoded Message received : " + message_received);
//byte[] input = Hex.decodeHex(it.next().message().toString().toCharArray());
//System.out.println("Deserializied Byte array : " + input);
byte[] received_message = it.next().message();
System.out.println(received_message);
Schema schema = null;
schema = new Schema.Parser().parse(new File("src/test_schema.avsc"));
DatumReader<GenericRecord> reader = new SpecificDatumReader<GenericRecord>(schema);
Decoder decoder = DecoderFactory.get().binaryDecoder(received_message, null);
GenericRecord payload2 = null;
payload2 = reader.read(null, decoder);
System.out.println("Message received : " + payload2);
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
}
}
测试 AVRO 模式:
{
"namespace": "xyz.test",
"type": "record",
"name": "payload",
"fields":[
{
"name": "name", "type": "string"
},
{
"name": "id", "type": ["int", "null"]
},
{
"name": "desc", "type": ["string", "null"]
}
]
}
需要注意的重要事项:
您需要标准的kafka和avro jars才能立即运行此代码。
很重要的是使用props.put("serializer.class", "kafka.serializer.DefaultEncoder");,不要使用stringEncoder,因为如果您发送字节数组作为消息,则它不起作用。
您可以将byte[]转换为十六进制字符串,并将其发送到消费者,然后将十六进制字符串重新转换为byte[],然后转换为原始消息。
按照这里所述运行zookeeper和broker:- http://kafka.apache.org/documentation.html#quickstart 并创建一个名为“page_views”的主题或任何您想要的主题。
运行ProducerTest.java,然后运行ConsumerGroupExample.java,查看生成和消费的avro数据。
我最终想起来询问Kafka邮件列表,并得到了下面的回答,这个方法非常有效:
是的,你可以发送字节数组作为消息。如果你看一下Message类的构造函数,你会发现-
def this(bytes: Array[Byte])
现在,再看一下Producer send() API -
def send(producerData: ProducerData[K,V]*)
你可以将V设置为Message类型,将K设置为你想要的键类型。如果你不关心使用键进行分区,则也可以将它设置为Message类型。
谢谢, Neha
如果您想从Avro消息中获取字节数组(kafka部分已经回答),请使用二进制编码器:
GenericDatumWriter<GenericRecord> writer = new GenericDatumWriter<GenericRecord>(schema);
ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
Encoder e = EncoderFactory.get().binaryEncoder(os, null);
writer.write(record, e);
e.flush();
byte[] byteData = os.toByteArray();
} finally {
os.close();
}
更新的回答。
Kafka有一个带有Maven(SBT格式)坐标的Avro序列化器/反序列化器:
"io.confluent" % "kafka-avro-serializer" % "3.0.0"
您需要在KafkaProducer构造函数中传递一个KafkaAvroSerializer实例。
然后,您可以创建Avro GenericRecord实例,并将其用作Kafka ProducerRecord实例中的值,然后使用KafkaProducer发送。
在Kafka消费者端,您需要使用KafkaAvroDeserializer和KafkaConsumer。
除了使用Avro之外,你也可以考虑压缩数据,可以使用gzip(压缩效果好但是占用CPU较高),也可以使用LZF或Snappy(速度快但是压缩效果稍差)。
或者你还可以考虑使用Smile二进制JSON格式,它被Jackson支持(使用这个扩展)。它是一种紧凑的二进制格式,比Avro更容易使用:
ObjectMapper mapper = new ObjectMapper(new SmileFactory());
byte[] serialized = mapper.writeValueAsBytes(pojo);
// or back
SomeType pojo = mapper.readValue(serialized, SomeType.class);
基本上与JSON相同的代码,只是传递了不同格式工厂。从数据大小的角度来看,Smile和Avro哪个更紧凑取决于使用情况的细节;但两者都比JSON更紧凑。
好处在于,这可以快速使用相同的代码和POJOs处理JSON和Smile。与需要代码生成或大量手动编写打包和解包GenericRecord
的Avro相比。