此为上一篇文章的续篇, kafka安装需要依赖zookeeper, 本文与上一篇文章都是真正分布式安装配置, 可以直接用于生产环境.
zookeeper安装参考:
http://blog.csdn.net/ubuntu64fan/article/details/26678877
假定我们有一个名称为test的topic, 分区数目为2, 当我们发送到这个test具体的消息"msg1:hello beijing"和"msg2:hello shanghai"的时候,我们如何知道消息的发送路径呢(发往哪个分区)? msg1如果被发送到分区test.1,则肯定不会发送到test.2. 数据发送路径选择决策受kafka.producer.Partitioner的影响: interface Partitioner { int partition(java.lang.Object key, int numPartitions); }
一个伪代码的实现如下:
package org.mymibao.mq.client;
import kafka.producer.Partitioner;
public class DefaultKafkaPartitioner implements Partitioner {
private final static int FIRST_PARTITION_ID = 1;
public int partition(Object key, int numPartitions) {
return FIRST_PARTITION_ID;
}
}
$ wget http://apache.fayea.com/apache-mirror/kafka/0.8.1.1/kafka_2.9.2-0.8.1.1.tgz
安装和配置参考上一篇文章:
http://blog.csdn.net/ubuntu64fan/article/details/26678877
2)配置$KAFKA_HOME/config/server.properties
我们安装3个broker,分别在3个vm上:zk1,zk2,zk3:
zk1:
$ vi /etc/sysconfig/network
NETWORKING=yes HOSTNAME=zk1
$ vi $KAFKA_HOME/config/server.properties
broker.id=0 port=9092 host.name=zk1 advertised.host.name=zk1 ... num.partitions=2 ... zookeeper.connect=zk1:2181,zk2:2181,zk3:2181
zk2:
$ vi /etc/sysconfig/network
NETWORKING=yes HOSTNAME=zk2
broker.id=1 port=9092 host.name=zk2 advertised.host.name=zk2 ... num.partitions=2 ... zookeeper.connect=zk1:2181,zk2:2181,zk3:2181
zk3:
$ vi /etc/sysconfig/network
NETWORKING=yes HOSTNAME=zk3
broker.id=2 port=9092 host.name=zk3 advertised.host.name=zk3 ... num.partitions=2 ... zookeeper.connect=zk1:2181,zk2:2181,zk3:2181
$ zkServer.sh start
$ kafka-server-start.sh $KAFKA_HOME/config/server.properties
$ kafka-topics.sh --create --topic test --replication-factor 3 --partitions 2 --zookeeper zk1:2181
列出已有的topics:
$ kafka-topics.sh --list --zookeeper zk1:2181
$ kafka-console-producer.sh --broker-list zk1:9092 --sync --topic test
在发送消息的终端输入:Hello Kafka
7)假设我们在zk3上,开一个终端,显示消息的消费(zk3模拟consumer)
$ kafka-console-consumer.sh --zookeeper zk1:2181 --topic test --from-beginning
在消费消息的终端显示:Hello Kafka
8) 编程操作Producer和Consumer的例子参考:
http://shift-alt-ctrl.iteye.com/blog/1930791