kafka集成springboot

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.6.1
        
        
    
    com.chen
    springboot-kafka
    1.0-SNAPSHOT

    
        8
        8
    
    
    
        org.springframework.boot
        spring-boot-starter-web
    
        
            org.springframework.kafka
            spring-kafka
        

        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.kafka
            spring-kafka-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    

application.properties

# 指定 kafka 的地址
spring.kafka.bootstrapservers=hadoop100:9092,hadoop101:9092,hadoop102:9092

#指定 key 和 value 的序列化器
spring.kafka.producer.keyserializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.valueserializer=org.apache.kafka.common.serialization.StringSerializer

#指定 key 和 value 的反序列化器
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer

#消费者组id
spring.kafka.consumer.group-id=chen

生产者

package com.chen.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProducerController {
    // Kafka 模板用来向 kafka 发送数据
    @Autowired
    KafkaTemplate kafka;

    @RequestMapping("/chen")
    public String data(String msg) {
        kafka.send("chen", msg);
        return "ok";
    }
}

消费者

package com.chen.springboot.controller;

import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;

@Configuration
public class ConsumerController {
    @KafkaListener(topics = "chen")
    public void consumerTopic(String msg){
        System.out.println("收到:"+msg);
    }
}

你可能感兴趣的:(kafka,大数据,Java,kafka,spring,boot,java)