kafka的原理
Producer:发送消息到kafka,kafka会以log的形式追加记录消息,并建立index(稀疏索引),向zookeeper发送消息,zookeeper记录kafka存放消息的offset
broker:以日志方式记录消息,并建立索引,不保存消息状态,状态由消费者,zookeeper共同维护
consumer:以pull的方式从kafka中拉取消息,处理完后并通知zookeeper修改消息状态,若zookeeper修改状态前,出故障或者异常,则此消息,可能会被多次消费,kafka保证消息不丢失
默认保存消息7天,即使删除,也只是标记并没有真的删除,真的删除需要修改配置文件
consumer会以CRC机制校验消息,保证消息的完整性
kafka自带测试zookeeper,配置conf下的zookeeper.properties文件
consumer可以分组,每个组对应一个topic,每个组中的消费者对应topic中的partition,一个partition只能被一个消费者消费,但是一个消费者可以消费多个partition
使用自带的zookeeper,测试要启动zookeeper-server-start.sh
伪分布安装:
生产者:
bin/kafka-console-producer.sh --broker-list 192.168.251.124:9092,192.168.251.125:9092,192.168.251.126:9092 --topic topic_notification_world_quant
集群安装:
安装zookeeper
见zookeeper安装
修改servier.properties文件
kafka存储消息以topic的方式,topic可以分为多个partition,生产者可以根据定义的类,默认random,往topic存放消息,topic根据定义的类,将消息存放到不同的partition中
consumer可以从指定的topic,topic指定的partition中取数据
Properties prop=new Properties();
prop.setProperties("zookeeper.connect","ip1:2181,ip2:2181:ip3:2181");
ConsumerConfig config=new ConsumerConfig(prop);
Consumer consumer=Consumer.createJavaConsumerConnector(config);
Map<String,Integer> topicCountMap=new HashMap<String,Integer>();
topicCountMap.put("topic",消费partition线程数);//指定partition线程数小于partition数,则某些线程消费多个partition,指定partition线程数大于partition数,则某些线程则永远等待,无法消费,建议指定消费线程数等于partition数
Map<String, List<KafkaStream<byte[], byte[]>>> messageStreams=consumer.createMessageStreams(Map<String, Integer> topicCountMap);
KafkaStream<byte[],byte[]> kafkaStream=messageStreams.get("topic").get(0);
ConsumerIterator<byte[],byte[]> iterator=kafkaStream.iterator();
while(iterator.hasNext()){
byte[] message=iterator.next().message();
System.out.println(message);
}
Properties prop=new Properties();
prop.setProperties("zookeeper.connect","ip1:2181,ip2:2181:ip3:2181");
prop.setProperties("serializer.class",StringEncoder.class);
prop.setProperties("metadata.broker.list","ip1:9092,ip2:9092,ip3:9093");
Producer producer=new Producer(new ProducerConfig(prop));
producer.send(new KeyedMessage("topic","message"));注意:在使用其他语言做客户端的时候,要配置server.properties文件中的advertised.host.name=服务器地址,默认值是host.name,host.name=localhost

浙公网安备 33010602011771号