[lch@linux129 bin]$ ./kafka-topics.sh --create --zookeeper hadoop221:2181,hadoop222:2181 --replication-factor 2 --partitions 2 --topic TEST_TTT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
class
KafkaAdmin{
public
static
void
main(String[] args) {
String[] arrys =
new
String[
6
];
arrys[
0
] =
"--replication-factor"
;
arrys[
1
] =
"1"
;
arrys[
2
] =
"--partitions"
;
arrys[
3
] =
"1"
;
arrys[
4
] =
"--topic"
;
arrys[
5
] =
"EFGH"
;
ZkClient client =
new
ZkClient(
"192.168.8.222:2181"
,
30000
,
30000
);
client.setZkSerializer(
new
ZKStringSerialize());
//一定要加上ZkSerializer
TopicCommandOptions opts =
new
TopicCommandOptions(arrys);
TopicCommand.createTopic(client, opts);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
public
class
ZKStringSerialize
implements
ZkSerializer {
@Override
public
byte
[] serialize(Object data)
throws
ZkMarshallingError {
if
(data
instanceof
String){
try
{
return
((String)data).getBytes(
"UTF-8"
);
}
catch
(UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return
null
;
}
@Override
public
Object deserialize(
byte
[] bytes)
throws
ZkMarshallingError {
if
(bytes ==
null
)
return
null
;
else
try
{
return
new
String(bytes,
"UTF-8"
);
}
catch
(UnsupportedEncodingException e) {
e.printStackTrace();
}
return
null
;
}
}
|
1
2
3
4
5
6
7
8
|
def
createTopic(...) {
//从zookeeper的/brokers/ids目录下面获取broker的列表信息
val
brokerList
=
ZkUtils.getSortedBrokerList(zkClient)
//此处会根据副本个数以及partition的个数,来分配broker节点, 即partition 0在哪几个节点上
val
replicaAssignment
=
AdminUtils.assignReplicasToBrokers(brokerList, partitions, replicationFactor)
//分配完成后,就开始创建节点信息
AdminUtils.createOrUpdateTopicPartitionAssignmentPathInZK(zkClient, topic, replicaAssignment, topicConfig)
}
|
1
2
3
4
5
6
7
8
|
def
createOrUpdateTopicPartitionAssignmentPathInZK(...) {
.... ....
// write out the config if there is any, this isn't transactional with the partition assignments
writeTopicConfig(zkClient, topic, config)
// create the partition assignment
writeTopicPartitionAssignment(zkClient, topic, partitionReplicaAssignment, update)
}
|
writeTopicConfig(zkClient, topic, config)
它创建的目录在zookeeper中的:
writeTopicPartitionAssignment(zkClient, topic, partitionReplicaAssignment, update)
创建完成后,就会在zookeeper中看到下面的这些东西。
client.setZkSerializer(
new
ZKStringSerialize()); 没有设置字符串序列化函数,导致topic创建目录失败,而kafka的listen线程发现有文件夹变化后,在创建时,无法获取相应的broker信息,因此创建失败了
2) producer产生的数据,只放在partiton 0中,而partition 1中总是没有数据。
原因: producer产生的数据会根据key来选择partition,而我的代码:
1
|
KeyedMessage km =
new
KeyedMessage<String, String>(
this
.topic,
"123"
,data);
|