一.centos安装kafka
1.下载kafka压缩包
wget https://www.apache.org/dyn/closer.cgi?path=/kafka/2.1.0/kafka_2.11-2.1.0.tgz
2.解压安装包
tar -zvxf kafka_2.11-2.1.0.tgz
3.启动zookeeper服务(cd进入解压包中)
bin/zookeeper-server-start.sh -daemon config/zookeeper.properties
4.启动kafka服务(守护线程启动)
bin/kafka-server-start.sh -daemon config/server.properties
5.测试是否启动成功(命令行 jps)
6.创建Topic
bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic levenx
查看Topic
bin/kafka-topics.sh --list --zookeeper localhost:2181
生成消息
bin/kafka-console-producer.sh --broker-list localhost:9092 --topic levenx
消费消息
bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic levenx --from-beginning
删除Topic
bin/kafka-topics.sh --delete --zookeeper localhost:2181 --topic levenx
二.springboot整合kafka
pom.xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
application.yml
spring:
kafka:
bootstrap-servers: 47.106.100.124:9092
consumer:
group-id: levenx
kafkaService
@Component
public class KafkaService {
private final Logger log = LoggerFactory.getLogger(KafkaService.class);
public static final String INDEX_TOPIC = "levenx";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private ObjectMapper objectMapper;
public void kakkaSend(String message) throws JsonProcessingException {
this.kafkaTemplate.send(INDEX_TOPIC, objectMapper.writeValueAsString(message));
}
@KafkaListener(topics = {INDEX_TOPIC})
public void kafkaRead(String msg){
log.info("====="+msg.toString());
}
}