本教程演示了如何发送和接收来自spring kafka的消息。 首先创建一个能够发送消息给kafka主题的spring kafka producer。 接下来,我们创建一个spring kafka consumer,它可以收听发送给kafka主题的消息。使用适当的键/值序列化器和解串器来配置它们。 最后用一个简单的spring boot应用程序演示应用程序。
下载并安装apache kafka
要下载并安装apache kafka,请阅读官方文档( https://kafka.apache.org/quickstart )。 本教程假设服务器使用默认配置启动,并且没有更改服务器端口。
maven依赖
这个项目中,使用apache maven来管理项目依赖关系。 确保以下依赖关系在类路径中。pom.xml 文件的内容如下所示 -
<project xmlns="http://maven.apache.org/pom/4.0.0"
xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
xsi:schemalocation="http://maven.apache.org/pom/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelversion>4.0.0</modelversion>
<groupid>com.h3.spring.kafka</groupid>
<artifactid>producer-consumer</artifactid>
<version>1.0.0-snapshot</version>
<url>https://www.h3.com/kafka</url>
<name>spring kafka - ${project.artifactid}</name>
<parent>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter-parent</artifactid>
<version>2.0.0.release</version>
</parent>
<properties>
<java.version>1.8</java.version>
<project.build.sourceencoding>utf-8</project.build.sourceencoding>
<spring-kafka.version>2.1.4.release</spring-kafka.version>
</properties>
<dependencies>
<dependency>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-starter</artifactid>
</dependency>
<dependency>
<groupid>org.springframework.kafka</groupid>
<artifactid>spring-kafka</artifactid>
<version>${spring-kafka.version}</version>
</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>
<version>${spring-kafka.version}</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupid>org.springframework.boot</groupid>
<artifactid>spring-boot-maven-plugin</artifactid>
</plugin>
</plugins>
<defaultgoal>compile</defaultgoal>
</build>
</project>
spring kafka发送消息到主题
使用producer的kafkatemplate类发送消息,并提供将数据发送到kafka主题的高级操作。 提供异步和同步方法,异步方法返回future。
package com.h3.kafka.producer;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.beans.factory.annotation.value;
import org.springframework.kafka.core.kafkatemplate;
import org.springframework.stereotype.service;
@service
public class sender {
private static final logger log = loggerfactory.getlogger(sender.class);
@autowired
private kafkatemplate<string, string> kafkatemplate;
@value("${app.topic.foo}")
private string topic;
public void send(string message){
log.info("sending message='{}' to topic='{}'", message, topic);
kafkatemplate.send(topic, message);
}
}
为了能成功地发送消息给kafka主题,我们需要配置kafkatemplate。 此配置由senderconfig类处理。
使用producerfactory的实现来配置kafkatemplate,更具体地说是使用defaultkafkaproducerfactory。可以使用map <string,object>来初始化这个生产者工厂,从producerconfig类获取的键。
producerconfig.bootstrap_servers_config指定用于建立到kafka集群的初始连接的主机/端口对列表。 客户端将使用所有服务器,而不管这里指定哪些服务器用于引导/此列表仅影响用于发现全套服务器的初始主机。 此列表应采用host1:port1,host2:port2,...的形式。由于这些服务器仅用于初始连接以发现完整集群成员资格(可能会动态更改),因此此列表不需包含完整集合 的服务器(不过,如果服务器停机,可能需要多个服务器)。
producerconfig.key_serializer_class_config指定实现org.apache.kafka.common.serialization.serializer接口的键的序列化程序类。
producerconfig.value_serializer_class_config指定实现org.apache.kafka.common.serialization.serializer接口的值的序列化程序类。
有关配置选项的完整列表,请查看producerconfig类(https://kafka.apache.org/10/javadoc/org/apache/kafka/clients/producer/producerconfig.html )。
package com.h3.kafka.producer;
import org.apache.kafka.clients.producer.producerconfig;
import org.apache.kafka.common.serialization.stringserializer;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.kafka.core.defaultkafkaproducerfactory;
import org.springframework.kafka.core.kafkatemplate;
import org.springframework.kafka.core.producerfactory;
import java.util.hashmap;
import java.util.map;
@configuration
public class senderconfig {
@value("${spring.kafka.bootstrap-servers}")
private string bootstrapservers;
@bean
public map<string, object> producerconfigs() {
map<string, object> props = new hashmap<>();
props.put(producerconfig.bootstrap_servers_config, bootstrapservers);
props.put(producerconfig.key_serializer_class_config, stringserializer.class);
props.put(producerconfig.value_serializer_class_config, stringserializer.class);
return props;
}
@bean
public producerfactory<string, string> producerfactory() {
return new defaultkafkaproducerfactory<>(producerconfigs());
}
@bean
public kafkatemplate<string, string> kafkatemplate() {
return new kafkatemplate<>(producerfactory());
}
}
spring kafka监听来自主题的消息
接下来,我们将演示如何监听来自kafka主题的消息。 receiver类将使用来自kafka主题的消息。 创建listen()方法并使用@kafkalistener注解对其进行了注释,该注释将方法标记为指定主题上的kafka消息侦听器的目标。
package com.h3.kafka.consumer;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.kafka.annotation.kafkalistener;
import org.springframework.messaging.handler.annotation.payload;
import org.springframework.stereotype.service;
@service
public class receiver {
private static final logger log = loggerfactory.getlogger(receiver.class);
@kafkalistener(topics = "${app.topic.foo}")
public void listen(@payload string message) {
log.info("received message='{}'", message);
}
}
该机制需要在@configuration类和侦听器容器工厂之一上使用@enablekafka注解,该工厂用于配置底层concurrentmessagelistenercontainer。
使用senderconfig类中使用的相同类型的键/值反序列化器是非常重要的。
consumerconfig.group_id_config指定一个唯一的字符串,标识此用户所属的用户组。consumerconfig.auto_offset_reset_config指定在kafka中没有初始偏移量或当前偏移量不再存在于服务器上(例如,因为该数据已被删除)时要执行的操作:earliest: 自动将偏移重置为最早的偏移量latest: 自动将偏移量重置为最新的偏移量none: 如果未找到消费者组的前一个偏移量,则向消费者抛出异常anything else: 向消费者抛出异常。消费者用消费者组名称标记自己,并且发布到主题的每个记录都被传送到每个订阅消费者组中的一个消费者实例。 消费者实例可以在单独的进程中或在单独的机器上。
如果所有消费者实例具有相同的消费者组,则记录将有效地在消费者实例上进行负载均衡。 如果所有消费者实例具有不同的消费者组,则每个记录将被广播到所有消费者进程。
有关配置选项的完整列表,请查看consumerconfig类(https://kafka.apache.org/10/javadoc/org/apache/kafka/clients/consumer/consumerconfig.html )。
package com.h3.kafka.consumer;
import org.apache.kafka.clients.consumer.consumerconfig;
import org.apache.kafka.common.serialization.stringdeserializer;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.kafka.annotation.enablekafka;
import org.springframework.kafka.config.concurrentkafkalistenercontainerfactory;
import org.springframework.kafka.config.kafkalistenercontainerfactory;
import org.springframework.kafka.core.consumerfactory;
import org.springframework.kafka.core.defaultkafkaconsumerfactory;
import org.springframework.kafka.listener.concurrentmessagelistenercontainer;
import java.util.hashmap;
import java.util.map;
@enablekafka
@configuration
public class receiverconfig {
@value("${spring.kafka.bootstrap-servers}")
private string bootstrapservers;
@bean
public map<string, object> consumerconfigs() {
map<string, object> props = new hashmap<>();
props.put(consumerconfig.bootstrap_servers_config, bootstrapservers);
props.put(consumerconfig.key_deserializer_class_config, stringdeserializer.class);
props.put(consumerconfig.value_deserializer_class_config, stringdeserializer.class);
props.put(consumerconfig.group_id_config, "foo");
props.put(consumerconfig.auto_offset_reset_config, "earliest");
return props;
}
@bean
public consumerfactory<string, string> consumerfactory() {
return new defaultkafkaconsumerfactory<>(consumerconfigs());
}
@bean
public kafkalistenercontainerfactory<concurrentmessagelistenercontainer<string, string>> kafkalistenercontainerfactory() {
concurrentkafkalistenercontainerfactory<string, string> factory = new concurrentkafkalistenercontainerfactory<>();
factory.setconsumerfactory(consumerfactory());
return factory;
}
}
使用application.yml配置应用程序
创建一个在src/main/resources文件夹中的application.yml属性文件。 这些属性通过spring引导注入到配置类中。
spring:
kafka:
bootstrap-servers: localhost:9092
app:
topic:
foo: foo.t
logging:
level:
root: error
org.springframework.web: error
com.h3: debug
运行应用程序
最后,编写一个简单的spring boot应用程序来演示应用程序。 为了使这个演示工作,需要在端口9092上运行的本地主机上的kafka服务器,这是kafka的默认配置。
在运行这个项目程序之前,需要运行 zookeeper 和 kafka ,如下所示 -
启动zookeeper服务 -
d:\software\kafka_2.12-1.0.1\bin\windows> zookeeper-server-start.bat d:\software\kafka_2.12-1.0.1\config\zookeeper.properties
启动kafka服务 -
d:\software\kafka_2.12-1.0.1\bin\windows> kafka-server-start.bat d:\software\kafka_2.12-1.0.1\config\server.properties
应用程序的实现 -
package com.h3.kafka;
import com.h3.kafka.producer.sender;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.boot.commandlinerunner;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
@springbootapplication
public class producerconsumerapplication implements commandlinerunner {
public static void main(string[] args) {
springapplication.run(producerconsumerapplication.class, args);
}
@autowired
private sender sender;
@override
public void run(string... strings) throws exception {
sender.send("spring kafka producer and consumer example");
}
}
当我们运行应用程序时,应该会得到类似下面的输出。
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: spring boot :: (v2.0.0.release)
2018-03-14 14:40:41.454 info 9740 --- [ main] c.y.kafka.producerconsumerapplication : starting producerconsumerapplication on my-pc with pid 9740 (f:\worksp\spring-kafka\producer-consumer\target\classes started by administrator in f:\worksp\spring-kafka\producer-consumer)
2018-03-14 14:40:41.458 debug 9740 --- [ main] c.y.kafka.producerconsumerapplication : running with spring boot v2.0.0.release, spring v5.0.4.release
2018-03-14 14:40:41.458 info 9740 --- [ main] c.y.kafka.producerconsumerapplication : no active profile set, falling back to default profiles: default
2018-03-14 14:40:47.512 info 9740 --- [ main] c.y.kafka.producerconsumerapplication : started producerconsumerapplication in 6.567 seconds (jvm running for 7.084)
2018-03-14 14:40:47.514 info 9740 --- [ main] com.h3.kafka.producer.sender : sending message='spring kafka producer and consumer example' to topic='foo.t'
2018-03-14 14:40:49.413 info 9740 --- [ntainer#0-0-c-1] com.h3.kafka.consumer.receiver : received message='spring kafka producer and consumer example'
