首先配置config目录下的文件
zookeeper.properties的dataDir路径任意
server.properties的log.dirs路径任意
安装文件目录下cmd
bin\windows\zookeeper-server-start.bat config\zookeeper.properties
安装目录下
bin\windows\kafka-server-start.bat config\server.properties
进入安装目录bin\windows目录下创建主题
kafka-topics.bat --create --bootstrap-server localhost:9092 --replication-factor 1 --partitions 1 --topic test
查看已创建的主题
kafka-topics.bat --list --bootstrap-server localhost:9092
使用生产者向刚建立的主题发送消息
kafka-console-producer.bat --broker-list localhost:9092 --topic test
然后输入消息回车即可
消费者消费消息
kafka-console-consumer.bat --bootstrap-server localhost:9092 --topic test --from-beginning
springboot配置kafka并且编写测试类
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
#kafkaProperties
spring.kafka.bootstrap-servers=localhost:9092
spring.kafka.consumer.group-id=test-consumer-group
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=3000
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
@ContextConfiguration(classes = CommunityApplication.class)
public class KafkaTests {
@Autowired
private KafkaProducer kafkaProducer;
@Test
public void testKafka() {
kafkaProducer.sendMessage("test", "你好!");
kafkaProducer.sendMessage("test", "在吗?");
try {
Thread.sleep(1000 * 10);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
@Component
class KafkaProducer {
@Autowired
private KafkaTemplate kafkaTemplate;
public void sendMessage(String topic, String content) {
kafkaTemplate.send(topic, content);
}
}
@Component
class KafkaConsumer {
@KafkaListener(topics = {"test"})
public void handleMessage(ConsumerRecord record) {
System.out.println(record.value());
}
}