栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot 使用 kafka

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot 使用 kafka

pom 文件添加依赖


    org.springframework.kafka
    spring-kafka

application.yml 文件添加配置

bootstrap-servers:是 broker 地址,如果是集群,则用逗号分隔

spring:
  kafka:
    bootstrap-servers: 192.168.140.xxx:xxxx,192.168.140.xxx:xxxx,192.168.140.xxx:xxxx

生产者

import com.njc.java.entity.api.resp.TestInfoRespDTO;
import com.njc.java.entity.base.NjcResponseEntity;
import com.njc.java.property.KafkaProperty;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class KafkaProducerController extends BaseController {

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    KafkaProperty kafkaProperty;

    
    @ApiOperation(value = "卡夫卡推送", notes = "卡夫卡推送")
    @PostMapping(value = "/kafka/{msg}")
    NjcResponseEntity sendKafka(@PathVariable("msg") String msg) {
        kafkaTemplate.send("topic", msg);
        return super.success("成功发送kafka", null);
    }
}

消费者

import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;
import java.util.Optional;


@Slf4j
@Component
public class KafkaConsumer {

    @KafkaListener(topics = "#{'${spring.kafka.topicDemo}'}", groupId = "a")
    public void ProductInsertEvent1(ConsumerRecord record) {
        Optional kafkaMessage = Optional.ofNullable(record.value());
        kafkaMessage.ifPresent(msg -> {
            log.info("KafkaConsumer1 kafka value:{}", msg);
        });
    }

    @KafkaListener(topics = "#{'${spring.kafka.topicDemo}'}", groupId = "b")
    public void ProductInsertEvent2(ConsumerRecord record) {
        Optional kafkaMessage = Optional.ofNullable(record.value());
        kafkaMessage.ifPresent(msg -> {
            log.info("KafkaConsumer2 kafka value:{}", msg);
        });
    }

}

相同 topic 如果不用 groupId 区分会报错
No group.id found in consumer config, container properties, or @KafkaListener annotation; a group.id is required when group management is used.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/959142.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号