springboot整合kafka

1.引入kakka依赖

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

2.修改配置文件

# 应用名称
spring.application.name=springboot-kafka

# 应用服务 WEB 访问端口
server.port=8080

# 连接kafka集群
spring.kafka.bootstrap-servers=8.8.80.8:9092

#key value的序列化
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=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=kafka-consumer-group

3.创建生产者

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 {

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    @RequestMapping("/kafka")
    public String data(String msg){
        // topic:“kafka”,msg:发送的消息
        kafkaTemplate.send("kafka", msg);

        return "ok";
    }
}

4. 创建消费者

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

@Configuration
public class KafkaConsumer {
    // 监听topics = "kafka"主题
    @KafkaListener(topics = "kafka")
    public void consumerTopic(String msg){
        System.out.println("收到消息:" + msg);
    }
}

5. 启动服务并发送消息

http://localhost:8080/kafka?msg=spring-boot-kafka

posted @ 2022-11-19 17:27  BlogMemory  阅读(256)  评论(0编辑  收藏  举报