kafka(一)
1.概述
kafka是一个开源流处理平台,一种高吞吐量的分布式发布订阅消息系统,它可以处理消费者在网站中的所有动作流数据。
2.生产者
处理过程
1).interceptors对消息进行拦截
2).Serializer对消息的key和value进行序列化
3).Partitioner为消息选择合适Patition
4).RecordAccumulator收集消息,实现批量发送。
5).Sender从RecordAccumulator获取消息
6).构造ClientRequest
7).将ClientRequest交给NetworkClient准备发送
8).NetworkClient将请求放入KafkaChannel的缓存
9).执行网络IO,发送请求
10).收到响应,调用ClientRequest的回调函数
11).调用RecordBatch上的回调函数,最终调用每个消息上注册的回调函数
3.demo
import org.apache.kafka.clients.producer.*; import org.apache.kafka.common.errors.RetriableException; import java.util.Properties; import java.util.concurrent.ExecutionException; public class KafkaProducerDemo { public static void main(String[] args) { Properties properties = new Properties(); properties.put("bootstrap.servers", "localhost:9092,localhost:9093,localhost:9094"); properties.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); properties.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); properties.put("acks", "-1"); System.out.println(ProducerConfig.ACKS_CONFIG); properties.put("retries", "3"); properties.put("batch.size", 1048576); //batch没有被填满,等待多久发送 properties.put("linger.ms", 10); //32MB 缓存消息的缓冲区大小 properties.put("buffer.memory", "33554432"); System.out.println(ProducerConfig.BUFFER_MEMORY_CONFIG); //压缩算法 properties.put(ProducerConfig.COMPRESSION_TYPE_CONFIG,"lz4"); properties.put("max.block.ms", "3000"); Producer<String, String> producer = new KafkaProducer<String, String>(properties); for (int i = 0; i < 10; i++) { producer.send(new ProducerRecord<String, String>("my-topic", Integer.toString(i), Integer.toString(i)), new Callback() { public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception == null) { System.out.println("success"); } else { System.out.println("fail"); if(exception instanceof RetriableException){ System.out.println("error"); }else { System.out.println("error2"); } } } }); ProducerRecord<String, String> producerRecord = new ProducerRecord<String, String>("test", Integer.toString(i)); try { RecordMetadata recordMetadata = producer.send(producerRecord).get(); System.out.println("result:" + recordMetadata.toString() + "," + recordMetadata.topic() + ", " + recordMetadata.partition()); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } producer.close(); } }