Kafka(四) :Java 编写简单的kafka生产者和消费者

一、准备工作

  • 框架:springboot
  • 电脑查看网关是否开启工具:telnet 安装(Mac)
  • 引入依赖:
 
 
   org.springframework.kafka
   spring-kafka
 

二、生产者

 public static void main(String[] args) {
        //创建生产者配置信息
        Properties properties = new Properties();
        //设置key
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        //设置重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
        //设置value
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,StringSerializer.class.getName());
        //设置服务地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"http://106.52.174.56:9092");

        //设置kafka
        KafkaProducer producers = new KafkaProducer(properties);
        //设置消息
        ProducerRecord producerRecords = new ProducerRecord<>("kafkalearn","learn-info","hello word!");
        //发送消息
        producers.send(producerRecords);
        //关闭
        producers.close();

    }

三、消费者

 public static void main(String[] args) {

        //创建消费者配置信息
        Properties properties = new Properties();
        //设置key
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class.getName());
        //设置消费组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG,"group.demo");
        //设置value
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,StringDeserializer.class.getName());
        //设置服务地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"http://106.52.174.56:9092");

        //设置kafka
        KafkaConsumer consumer = new KafkaConsumer(properties);
        //订阅消息
        consumer.subscribe(Collections.singletonList("kafkalearn"));
        //监听消息,间隔2秒轮询一次
        while (true){
            ConsumerRecords poll = consumer.poll(Duration.ofMillis(2000));
            poll.forEach(item->{
                System.out.println("结果呢:----"+item.key()+"--"+item.value());
            });

        }

五、出现的问题

  1. centeros上本地连接不上,报错,
  •   解决办法:无法远程连接kafka

你可能感兴趣的:(#,Kafka)