初识kafka,以及springboot接入

kafka使用scala编写,采用zookeeper作为服务注册发现中心,下载地址以及安装启动过程如下,我的安装目录是/Users/r/services/kafka:

核心:

 

 

创建topic test

[root@uds-gww2 kafka]# ./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test

Created topic test.

[root@uds-gww2 kafka]#

 

显示topic列表

[root@uds-gww2 kafka]# ./bin/kafka-topics.sh --list --zookeeper localhost:2181

test

[root@uds-gww2 kafka]#

 

预先创建topic的情景:

生产:

[root@uds-gww2 kafka]# ./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test

>asfd

>asdf

>^C[root@uds-gww2 kafka]#

 

消费:

[root@uds-gww2 kafka]# ./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning

asfd

asdf

^CProcessed a total of 2 messages

[root@uds-gww2 kafka]#

 

topic没有被预先创建的情景:

生产:

[root@uds-gww2 kafka]# ./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic test2

>asfwr

[2019-04-09 02:04:07,594] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 3 : {test2=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)

[2019-04-09 02:04:07,697] WARN [Producer clientId=console-producer] Error while fetching metadata with correlation id 4 : {test2=LEADER_NOT_AVAILABLE} (org.apache.kafka.clients.NetworkClient)

>^C[root@uds-gww2 kafka]#

消费:

[root@uds-gww2 kafka]# ./bin/kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test2 --from-beginning

asfwr

^CProcessed a total of 1 messages

[root@uds-gww2 kafka]#

 

再次显示topic列表:

[root@uds-gww2 kafka]# ./bin/kafka-topics.sh --list --zookeeper localhost:2181

__consumer_offsets

test

test2

[root@uds-gww2 kafka]#

 

kafka-manager的dashboard如下:http://localhost:9080/

 

下面创建springboot项目kafka-hello,引入依赖:spring-kafka

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

配置属性文件application.properties: 其中的地址是zookeeper的地址

spring.kafka.bootstrap-servers=127.0.0.1:9092
spring.kafka.consumer.group-id=test1

定义生产者:

package com.sc.kafkahello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;


@Component
public class Sender {

    @Autowired
    private KafkaTemplate kafkaTemplate;


    public void send(String msg) {
        ListenableFuture listenableFuture = this.kafkaTemplate.send("test1", msg);
    }
}

定义消费者:

package com.sc.kafkahello;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;


@Component
public class Sender {

    @Autowired
    private KafkaTemplate kafkaTemplate;


    public void send(String msg) {
        ListenableFuture listenableFuture = this.kafkaTemplate.send("test1", msg);
    }
}

测试例子:

package com.sc.kafkahello;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaHelloApplicationTests {

    @Autowired
    private Sender sender;

    @Test
    public void contextLoads() {
        this.sender.send((new Date()).toString());
    }

}

先运行程序,再运行测试例子,观察到消息消费:

命令行也能同步消费消息:

 

 

### Spring Boot 整合 Kafka 示例教程 #### 1. 添加依赖 要在 Spring Boot 项目中集成 Kafka,首先需要在 `pom.xml` 文件中添加相应的 Maven 依赖: ```xml <dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency> ``` 这一步骤确保了项目能够访问到必要的 Kafka 客户端库和 Spring Kafka 支持的功能[^2]。 #### 2. 配置 Kafka 连接 接下来,在项目的配置文件 (`application.properties` 或者 `application.yml`) 中设置 Kafka 的连接参数。以下是基于 YAML 格式的配置示例: ```yaml spring: kafka: bootstrap-servers: localhost:9092 consumer: group-id: my-group auto-offset-reset: earliest ``` 这些属性指定了 Kafka broker 地址、消费者组 ID 和偏移量重置策略等重要信息[^1]。 #### 3. 创建生产者组件 定义一个用于发送消息至指定主题 (topic) 的生产者类。通过注入 `KafkaTemplate<String, String>` 来简化操作过程: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Service; @Service public class ProducerService { private final KafkaTemplate<String, String> kafkaTemplate; @Autowired public ProducerService(KafkaTemplate<String, String> kafkaTemplate) { this.kafkaTemplate = kafkaTemplate; } public void sendMessage(String topicName, String message){ System.out.println("Producing Message : "+message); kafkaTemplate.send(topicName,message); } } ``` 此代码片段展示了如何利用 Spring 提供的模板来封装底层细节并提高编码效率[^3]。 #### 4. 实现消费者逻辑 同样地,创建另一个服务类负责监听特定的主题并将收到的数据处理完毕后打印出来: ```java import org.apache.kafka.clients.consumer.ConsumerRecord; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.stereotype.Service; @Service public class ConsumerService { @KafkaListener(topics = "${spring.kafka.topic.name}", groupId="${spring.kafka.consumer.group-id}") public void listen(ConsumerRecord<Integer, String> record) throws Exception{ System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(),record.key(),record.value()); } } ``` 这里使用了 `@KafkaListener` 注解自动注册监听器,并且可以根据传入的消息执行自定义业务流程。 #### 5. 启动应用程序测试功能 完成上述步骤之后就可以启动整个应用来进行简单的收发测试了。当程序运行起来以后,任何向目标 Topic 发送的新消息都会触发对应的消费行为。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值