pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.cpc</groupId>
<artifactId>springbootkafuka</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springbootkafuka</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</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</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
项目结构
消息实体类 Message
package com.cpc.springbootkafuka.beans;
import lombok.Data;
import java.util.Date;
/**
* @author cpc
* @site www.cpc.com
* @company xxx公司
* @create 2019-09-23 15:45
*/
@Data
public class Message {
private Long id; //id
private String msg; //消息
private Date sendTime; //时间戳
}
消息生成者 负责发送消息 KafkaSender
package com.cpc.springbootkafuka.provider;
import com.cpc.springbootkafuka.beans.Message;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.UUID;
/**
* @author cpc
* @site www.cpc.com
* @company xxx公司
* @create 2019-09-23 15:46
*/
@Component
@Slf4j
public class KafkaSender {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
private Gson gson = new GsonBuilder().create();
//发送消息方法
public void send() {
Message message = new Message();
message.setId(System.currentTimeMillis());
message.setMsg(UUID.randomUUID().toString());
message.setSendTime(new Date());
log.info("+++++++++++++++++++++ message = {}", gson.toJson(message));
//请注意:message 就是要发送的主题
kafkaTemplate.send("message", gson.toJson(message));
}
}
这里关键的代码为 kafkaTemplate.send()方法,message是 Kafka 里的 topic ,这个 topic 在 Java 程序中是不需要提前在 Kafka 中设置的,因为它会在发送的时候自动创建你设置的 topic, gson.toJson(message)是消息内容
消息消费者 负载处理队列里头的消息 KafkaReceiver
package com.cpc.springbootkafuka.consumer;
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;
/**
* @author cpc
* @site www.cpc.com
* @company xxx公司
* @create 2019-09-23 15:48
*/
@Component
@Slf4j
public class KafkaReceiver {
/**
*这里非常的简单,就是将监听 message 这个队列中值的变化。当
* message 中发送变换的时候 就会触发此回调。当然按可以监听多个 因为 topics 是一个数组嘛
* @param record
*/
@KafkaListener(topics = {"message"})
public void listen(ConsumerRecord<?, ?> record) {
Optional<?> kafkaMessage = Optional.ofNullable(record.value());
if (kafkaMessage.isPresent()) {
Object message = kafkaMessage.get();
log.info("----------------- record =" + record);
log.info("------------------ message =" + message);
}
}
}
客户端 consumer 接收消息特别简单,直接用 @KafkaListener 注解即可,并在监听中设置监听的 topic ,topics 是一个数组所以是可以绑定多个主题的,上面的代码中修改为 @KafkaListener(topics = {“message”,“kafka”}) 就可以同时监听两个 topic 的消息了。需要注意的是:这里的 topic 需要和消息发送类 KafkaSender.java 中设置的 topic 一致。
application.properties 置文件
#============== kafka ===================
# 指定kafka 代理地址,可以多个
spring.kafka.bootstrap-servers=192.168.43.139:9092
#=============== provider =======================
spring.kafka.producer.retries=0
# 每次批量发送消息的数量
spring.kafka.producer.batch-size=16384
spring.kafka.producer.buffer-memory=33554432
# 指定消息key和消息体的编解码方式
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
#=============== consumer =======================
# 指定默认消费者group id
spring.kafka.consumer.group-id=test-consumer-group
spring.kafka.consumer.auto-offset-reset=earliest
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.consumer.auto-commit-interval=100
# 指定消息key和消息体的编解码方式
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.bootstrap-servers 后面设置你安装的 Kafka 的机器 IP 地址和端口号 9092。
如果你只是简单整合下,其他的几个默认就好了。
SpringbootkafukaApplication 启动类
@SpringBootApplication
public class SpringbootkafukaApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(SpringbootkafukaApplication.class, args);
KafkaSender sender = context.getBean(KafkaSender.class);
for (int i = 0; i < 3; i++) {
//调用消息发送类中的消息发送方法
sender.send();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
kafka服务配置修改和启动
config/server.properties将listeners 配置修改成如下格式:
listeners=PLAINTEXT://你的ip地址:9092
例如:
listeners=PLAINTEXT://192.168.43.139:9092
运行 zookepper
bin/zookeeper-server-start.sh config/zookeeper.properties &
运行 kafka
bin/kafka-server-start.sh config/server.properties &
开发端口和更新防火墙规则
firewall-cmd --zone=public --add-port=9092/tcp --permanent
firewall-cmd --reload
测试:
直接运行启动类,看控制台输出
转载:https://blog.csdn.net/qq_43059674/article/details/101215694