当前位置:   article > 正文

Springboot-kafka的入门使用_springboot kafka使用

springboot kafka使用

Springboot-kafka的入门使用

1. 导入依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.kafka</groupId>
            <artifactId>spring-kafka-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27

2. 编写消费者和生产者配置

spring:
  application:
    name: sringboot-kafka-lemon

  kafka:
    # 指定kafka地址
    bootstrap-servers: 172.17.10.110:9092
    # 配置指定的key和value的序列化器
    producer:
      key-serializer: org.apache.kafka.common.serialization.StringSerializer
      value-serializer: org.apache.kafka.common.serialization.StringSerializer

    # 配置指定的key和value的反序列化器
    consumer:
      key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
      # 指定消费者组
      group-id: lemon
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

3. ProducerController

@RestController
public class ProducerController {

    @Autowired
    KafkaTemplate<String,String> kafkaTemplate;

    /**
     * 发送到指定的topic
     */
    @RequestMapping("/send")
    public String send(String msg){
        kafkaTemplate.send("firstSend", msg);
        return "发送成功";
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

4. Kafkaconsumer

@Component
public class KafkaConsumer {
    @KafkaListener(topics = "firstSend")
    public void  consumerTopics(String msg){
        System.out.println("receive:"+msg);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

5. 测试

localhost:8080/send/msg="hello,kafka“

测试

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/923324
推荐阅读
相关标签
  

闽ICP备14008679号