SpringBoot -- Kafka(二) Demo

前置工作

  • Kafka 、zookeeper环境已经完成
  • JDK完成安装(kafka环境依赖jvm)
  • 了解kafka、zookeeper各种的作用

Demo

  • 依然使用现有的feignserver
  • 有说Springboot 1.5+ 已经支持spring-integration 无缝对接
  • 本文依然使用的 1.4+,所以还是采用config方式

引入kafka依赖

build.gradle

compile ('org.springframework.integration:spring-integration-core:4.3.6.RELEASE')
compile ('org.springframework.kafka:spring-kafka:1.1.0.RELEASE')

配置参数:broker、zk、group等
application.yml

bootcwenao:
  kafka:
    binder:
      brokers: localhost:9092
      zk-nodes: localhost:2181
    group: cwenao-group

创建KafkaProducersConfig并使用@Configuration、@EnableKafka

/**
 * @author cwenao
 * @version $Id KafkaConfig.java, v 0.1 2017-01-20 9:51 cwenao Exp $$
 */

@Configuration
@EnableKafka
public class KafkaProducersConfig {
    @Value("${bootcwenao.kafka.binder.brokers}")
    private String brokers;

    @Bean("kafkaTemplate")
    public KafkaTemplate<String, String> kafkaTemplate() {
        KafkaTemplate<String, String> kafkaTemplate = new KafkaTemplate<String, String>(producerFactory());
        return kafkaTemplate;
    }

    public ProducerFactory<String, String> producerFactory() {

        // set the producer properties
        Map<String, Object> properties = new HashMap<String, Object>();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
        properties.put(ProducerConfig.RECEIVE_CONFIG, 0);
        properties.put(ProducerConfig.BATCH_SIZE_CONFIG, 4096);
        properties.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        properties.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 40960);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);

        return new DefaultKafkaProducerFactory<String, String>(properties);
    }
}

创建Listener 处理消息,使用@KafkaListener,用户监听topic

/**
 * @author cwenao
 * @version $Id KafkaListeners.java, v 0.1 2017-01-21 21:31 cwenao Exp $$
 */
public class KafkaListeners {

    @KafkaListener(topics = {"bootcwenaoTopic"})
    public void testListener(ConsumerRecord<?, ?> record) {

        Optional<?> messages = Optional.ofNullable(record.value());

        if (messages.isPresent()) {
            Object msg = messages.get();
            System.out.println("  this is the testTopic send message: " + msg);
        }
    }
}

创建KafkaConsumerConfig并使用@Configuration、@EnableKafka

/**
 * @author cwenao
 * @version $Id KafkaConsumerConfig.java, v 0.1 2017-01-21 21:11 cwenao Exp $$
 */
@Configuration
@EnableKafka
public class KafkaConsumerConfig {

    @Value("${bootcwenao.kafka.binder.brokers}")
    private String brokers;

    @Value("${bootcwenao.kafka.group}")
    private String group;

    @Bean
    public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {

        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<String, String>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(4);
        factory.getContainerProperties().setPollTimeout(4000);

        return factory;
    }

    @Bean
    public KafkaListeners kafkaListeners() {
        return new KafkaListeners();
    }

    public ConsumerFactory<String, String> consumerFactory() {

        Map<String, Object> properties = new HashMap<String, Object>();

        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, brokers);
        properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
        properties.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, group);
        properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "latest");

        return new DefaultKafkaConsumerFactory<String, String>(properties);
    }
}

测试

创建生产者发送信息方法testKafka

/**
 * @author cwenao
 * @version $Id FeignController.java, v 0.1 2017-01-15 13:50 cwenao Exp $$
 */
@Controller
public class FeignController {

    @Autowired
    KafkaTemplate kafkaTemplate;

    @RequestMapping("/testKafka")
    @ResponseBody

    public void testkafka(String message) {
        kafkaTemplate.send("bootcwenaoTopic", "bootcwnao", message);
    }
}

依次启动 discovery、configserver、 apigateway、feignserver

浏览器中输入 http://localhost:10002/servers/testKafka?message=aaaaaaaaaaabbbbb

可以看到KafkaListeners中输出 this is the testTopic send message: aaaaaaaaaaabbbbb

可能的错误


  • kafka版本不对,现在这种方式只能支持0.10.x.x
  • kafka配置没有对外开放host、port

  • advertised.host.name、advertised.port
  • broker-list配置的不对

代码

代码请移步 Github参考地址

如有疑问请加公众号(K171),如果觉得对您有帮助请 github start
公众号_k171

Spring Boot中连接Kafka,你可以通过以下步骤进行操作: 1. 首先,在你的Spring Boot应用程序中添加Kafka的依赖。可以在pom.xml文件中添加以下Maven依赖: ```xml <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> ``` 2. 创建Kafka生产者。你可以创建一个类,例如`DemoKafkaProducerApplication`,并在其中添加`@SpringBootApplication`注解。同时,你还需要在该类中创建一个`KafkaAdmin.NewTopics`的Bean,用于创建Kafka主题。你可以使用`TopicBuilder`来定义主题的名称和其他属性。以下是一个示例代码: ```java @SpringBootApplication public class DemoKafkaProducerApplication { public static void main(String[] args) { SpringApplication.run(DemoKafkaProducerApplication.class, args); } @Bean public KafkaAdmin.NewTopics topics() { return new KafkaAdmin.NewTopics(TopicBuilder.name(KafkaMessageConst.KAFKA_TOPIC_DEMO).build()); } } ``` 请注意,`KafkaMessageConst.KAFKA_TOPIC_DEMO`是一个主题的常量,你可以根据自己的需求进行修改。这个常量定义可以在`KafkaMessageConst`类中找到。 3. 现在,你的Spring Boot应用程序已经可以连接Kafka了。你可以使用Spring Kafka提供的工具类和注解来创建Kafka生产者和消费者,并进行消息的发送和接收。 希望这些信息对你有帮助!<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [SpringBoot 2.6 集成 Kafka 2.8](https://blog.csdn.net/Mrqiang9001/article/details/123212777)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值