该项目是使用的技术:SpringBoot + SpringKafka + Maven
先看pom.xml文件中引入的依赖:
1 24 4.0.0 5 6com.xuebusi.producer 7producer 80.0.1-SNAPSHOT 9jar 10 11springkafkaproducer 12Demo project for Spring Boot 13 1415 20 21org.springframework.boot 16spring-boot-starter-parent 171.5.8.RELEASE 1819 22 26 27UTF-8 23UTF-8 241.8 2528 48 4929 32org.springframework.boot 30spring-boot-starter-freemarker 3133 37org.springframework.kafka 34spring-kafka 351.0.6.RELEASE 3638 41 42org.springframework.boot 39spring-boot-starter-web 4043 47org.springframework.boot 44spring-boot-starter-test 45test 4650 57 58 5951 5652 55org.springframework.boot 53spring-boot-maven-plugin 54
注意:这里我使用的spring-kafka(它包装了apache的kafka-client)的依赖包版本是 1.0.6.RELEASE, 是因为我Linux服务器上部署的kafka服务器的版本是kafka_2.10-0.9.0.1,使用的kafka的时候要注意,kafka客户端(kafka-client)的版本要和kafka服务器的版本一一对应,否则,消息发送会失败。
Spring官方网站上给出了SpringKafka和kafka-client版本(它的版本号要和kafka服务器的版本保持一致)的对应关系:
https://projects.spring.io/spring-kafka/
下面是生产者的配置文件,既然使用的是SpringBoot,配置文件就是 application.yml:
server: port: 8081spring: kafka: producer: bootstrap-servers: 192.168.71.11:9092,192.168.71.12:9092,192.168.71.13:9092
在上面的配置中,我们给生产者分配的端口号是8081,服务器有3台,分别对应3个ip地址和端口。
该配置只是配置了kafka服务器的ip地址,这里并没有对生产者做过多的配置。想了解关于kafka生产者相关的更多配置的话,可以自行查阅相关资料进行学习。
下面是kafka生产者的核心代码,实现了消息的发送逻辑:
package com.xuebusi.producer;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.kafka.core.KafkaTemplate;import org.springframework.scheduling.annotation.EnableScheduling;import org.springframework.scheduling.annotation.Scheduled;import org.springframework.stereotype.Component;import org.springframework.util.concurrent.ListenableFuture;import java.util.UUID;/** * 生产者 * 使用@EnableScheduling注解开启定时任务 */@Component@EnableSchedulingpublic class KafkaProducer { @Autowired private KafkaTemplate kafkaTemplate; /** * 定时任务 */ @Scheduled(cron = "00/1 * * * * ?") public void send(){ String message = UUID.randomUUID().toString(); ListenableFuture future = kafkaTemplate.send("app_log", message); future.addCallback(o -> System.out.println("send-消息发送成功:" + message), throwable -> System.out.println("消息发送失败:" + message)); }}
在上面的代码中,负责发送消息的角色就是SpringKafka提供的 KafkaTemplate对象,使用它的 send()方法就可以把自己的消息发送到kafka服务器。send()方法有多个重载的方法,大家可以根据自己的需要来使用不同的send()方法。
这里我们为了方便发送消息进行测试,使用了Spring的定时任务,在类上使用 @EnableScheduling 注解开启定时任务,在方法上使用@Scheduled注解并指定表达式来定义定时规则,这里我们每秒就会向kafka服务器发送一条消息。
当然,你可能不会用到Spring的定时任务,你可以把@EnableScheduling 和 @Scheduled注解去掉。你也可以通过使用Spring的@Controller和@RequestMapping 注解将你的发送消息的方法定义成一个接口。
你可以定义多个不同的方法,每个使用到了 KafkaTemplate 对象的方法都会是一个生产者。
下面就启动SpringBoot项目测试:
package com.xuebusi;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplicationpublic class SpringkafkaproducerApplication { public static void main(String[] args) { SpringApplication.run(SpringkafkaproducerApplication.class, args); }}
使用鼠标右键运行main方法即可启动SpringBoot项目,在控制台你会看到成功连接到kafka服务器,并每隔1秒就会发送一条消息到kafka服务器。