Kafka(四) :Java 編寫簡單的kafka生產者和消費者

一、準備工作

 <!--添加kafka -->
 <dependency>
   <groupId>org.springframework.kafka</groupId>
   <artifactId>spring-kafka</artifactId>
 </dependency>

二、生產者

 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<String, String> producers = new KafkaProducer<String, String>(properties);
        //設置消息
        ProducerRecord<String,String> 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<String, String> consumer = new KafkaConsumer<String, String>(properties);
        //訂閱消息
        consumer.subscribe(Collections.singletonList("kafkalearn"));
        //監聽消息,間隔2秒輪詢一次
        while (true){
            ConsumerRecords<String, String> poll = consumer.poll(Duration.ofMillis(2000));
            poll.forEach(item->{
                System.out.println("結果呢:----"+item.key()+"--"+item.value());
            });

        }

五、出現的問題

  1. centeros上本地連接不上,報錯,
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章