(1)JDK安装 1.8.0_121
(2)zookeeper安装 3.6.3
(3)kafka的安装
版本:kafka_2.11-2.0.0
这里补充点:server.properties中zookeeper.connect=localhost:2181,最好修改为:zookeeper.connect=localhost:2181/kafka。明确指明该chroot路径下的节点是为kafka所有的,可以实现多个kafka集群复用一天zookeeper集群,可以节省更多硬件资源。
(4)常用命令
创建Topic:
kafka-topics.bat --create --zookeeper localhost:2181/kafka --topic message --partitions 1 --replication-factor 1
查看topic:kafka-topics.bat --zookeeper localhost:2181/kafka --describe --topic message
(5)写了个demo:
消息生产者:
@Controller
public class KafkaDemo {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@RequestMapping("sendMsg")
@ResponseBody
public String sendMsgToKafka() {
//send(topic:主题,data:数据)
kafkaTemplate.send("message", "hello,Kafka!");
return "发送消息到Kafka完毕";
}
}
消息消费者
@Component
public class KafkaConsumer {
@KafkaListener(topics = {"message"})
public void listen(ConsumerRecord<?, ?> record) {
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
Object message = kafkaMessage.get();
System.out.println("数据接收完毕:"+message);
}
}
}
自己调试好的demo链接:https://download.csdn.net/download/spark_guo/81883655