springboot整合kafka消息队列

1.启动项目之前先启动zookooper 和 kafka服务

2.pom


    org.springframework.kafka
    spring-kafka
    2.4.1.RELEASE

3.yml

spring:
  kafka:
    auto-create-topics: true
    bootstrap-servers: localhost:9092
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer
    consumer:
      group-id: bei
      enable-auto-commit: true
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer

4.生产者

/**
 * @author bei
 * @2020/1/17 15:06
 * 生成者
 */
@RestController
@RequestMapping("/kafka")
public class KafkaProducerController {
    @Autowired
    private KafkaTemplate kafkaTemplate;

    @RequestMapping("/send")
    public R testSend(){
        kafkaTemplate.send("bei", "bei");
        return R.ok();
    }
}

5.消费者

/**
 * @author bei
 * @2020/1/17 15:09
 * 消费者
 */
@Component
public class KafkaConsumer {
    @KafkaListener(topics = "bei")
    public void listen(ConsumerRecord record){
        System.out.println(record.topic());
        System.out.println(record.offset());
        System.out.println(record.value());
    }
}

 

6.如果启动出现主题不存在的情况

Topic(s) is/are not present and missingTopicsFatal is true

windows/kafka-topics.bat --create --topic topicname --replication-factor 1 --partitions 1 --zookeeper localhost:2181 

--topic 指定topic名字

手动创建主题即可解决问题

你可能感兴趣的:(学习笔记)