赞
踩
在pom.xml文件中添加Kafka的依赖
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
在生产者项目
的application.properties文件中配置kafka
spring.kafka.bootstrap-servers=192.168.56.100:9092
spring.kafka.producer.client-id=forlan-client-id
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
参数说明:
在消费者项目
的application.properties文件中配置kafka消费者
spring.kafka.bootstrap-servers=192.168.56.100:9092
spring.kafka.consumer.client-id=forlan-client-id
spring.kafka.consumer.group-id=forlan-group-id
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
参数说明:
设置发送消息服务类
@Component
public class KafkaProducer {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void testSend(String topic, String message) throws ExecutionException, InterruptedException {
SendResult<String, String> stringStringSendResult = kafkaTemplate.send(topic, message).get();
System.out.println(stringStringSendResult);
}
}
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumer {
@KafkaListener(topics = "forlan_topic")
public void listen(String message) {
System.out.println("Kafka收到消息:" + message);
}
}
编写测试类,发送消息
@Autowired
private KafkaProducer kafkaProducer;
@Test
public void testKafka() throws ExecutionException, InterruptedException {
kafkaProducer.testSend("forlan_topic", "Forlan测试发送Kafka消息"+ LocalDateTime.now());
}
执行测试类,效果如下:
消费者后,会收到消息,如下:
[Consumer clientId=consumer-forlan-group-id-1, groupId=forlan-group-id] Connection to node 1001 (localhost/127.0.0.1:9092) could not be established. Broker may not be available.
由于我们的kafka是装在容器内,使用下面这种方式,localhost指的是容器的ip,会有问题
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
正确的做法,应该是改为我们宿主机的ip,如下:
KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://192.168.56.100:9092
其实就是把localhost设置为具体的ip,宿主机的ip。
[Producer clientId=forlan-client-id-1] Error while fetching metadata with correlation id 3 : {forlan-topic=LEADER_NOT_AVAILABLE}
重启kafka即可
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。