<dependency> <groupId>org.springframework.kafka</groupId> <artifactId>spring-kafka</artifactId> </dependency>
spring: #kafka配置 kafka: #这里改成你的kafka服务器ip和端口号 bootstrap-servers: 10.24.19.237:9092 #=============== producer ======================= producer: #若是该值大于零时,表示启用重试失败的发送次数 retries: 0 #每当多个记录被发送到同一分区时,生产者将尝试将记录一块儿批量处理为更少的请求,默认值为16384(单位字节) batch-size: 16384 #生产者可用于缓冲等待发送到服务器的记录的内存总字节数,默认值为3355443 buffer-memory: 33554432 #key的Serializer类,实现类实现了接口org.apache.kafka.common.serialization.Serializer key-serializer: org.apache.kafka.common.serialization.StringSerializer #value的Serializer类,实现类实现了接口org.apache.kafka.common.serialization.Serializer value-serializer: org.apache.kafka.common.serialization.StringSerializer #=============== consumer ======================= consumer: #用于标识此使用者所属的使用者组的惟一字符串 group-id: test-consumer-group #当Kafka中没有初始偏移量或者服务器上再也不存在当前偏移量时该怎么办,默认值为latest,表示自动将偏移重置为最新的偏移量 #可选的值为latest, earliest, none auto-offset-reset: earliest #消费者的偏移量将在后台按期提交,默认值为true enable-auto-commit: true #若是'enable-auto-commit'为true,则消费者偏移自动提交给Kafka的频率(以毫秒为单位),默认值为5000。 auto-commit-interval: 100 #密钥的反序列化器类,实现类实现了接口org.apache.kafka.common.serialization.Deserializer key-deserializer: org.apache.kafka.common.serialization.StringDeserializer #值的反序列化器类,实现类实现了接口org.apache.kafka.common.serialization.Deserializer value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
package com.example.study.util; import com.google.common.collect.Lists; import org.apache.kafka.clients.admin.*; import org.apache.kafka.common.TopicPartitionInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Collectors; /** * 操做kafka的工具类 * * @author 154594742@qq.com * @date 2021/3/2 14:52 */ @Component public class KafkaUtils { @Value("${spring.kafka.bootstrap-servers}") private String springKafkaBootstrapServers; private AdminClient adminClient; @Autowired private KafkaTemplate kafkaTemplate; /** * 初始化AdminClient * '@PostConstruct该注解被用来修饰一个非静态的void()方法。 * 被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,而且只会被服务器执行一次。 * PostConstruct在构造函数以后执行,init()方法以前执行。 */ @PostConstruct private void initAdminClient() { Map<String, Object> props = new HashMap<>(1); props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, springKafkaBootstrapServers); adminClient = KafkaAdminClient.create(props); } /** * 新增topic,支持批量 */ public void createTopic(Collection<NewTopic> newTopics) { adminClient.createTopics(newTopics); } /** * 删除topic,支持批量 */ public void deleteTopic(Collection<String> topics) { adminClient.deleteTopics(topics); } /** * 获取指定topic的信息 */ public String getTopicInfo(Collection<String> topics) { AtomicReference<String> info = new AtomicReference<>(""); try { adminClient.describeTopics(topics).all().get().forEach((topic, description) -> { for (TopicPartitionInfo partition : description.partitions()) { info.set(info + partition.toString() + "\n"); } }); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return info.get(); } /** * 获取所有topic */ public List<String> getAllTopic() { try { return adminClient.listTopics().listings().get().stream().map(TopicListing::name).collect(Collectors.toList()); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } return Lists.newArrayList(); } /** * 往topic中发送消息 */ public void sendMessage(String topic, String message) { kafkaTemplate.send(topic, message); } }
package com.example.study.controller; import com.example.study.model.vo.ResponseVo; import com.example.study.util.BuildResponseUtils; import com.example.study.util.KafkaUtils; import com.google.common.collect.Lists; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import org.apache.kafka.clients.admin.NewTopic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.kafka.annotation.KafkaListener; import org.springframework.web.bind.annotation.*; import java.util.List; /** * kafka控制器 * * @author 154594742@qq.com * @date 2021/3/2 15:01 */ @RestController @Api(tags = "Kafka控制器") @Slf4j public class KafkaController { @Autowired private KafkaUtils kafkaUtils; /** * 新增topic (支持批量,这里就单个做为演示) * * @param topic topic * @return ResponseVo */ @ApiOperation("新增topic") @PostMapping("kafka") public ResponseVo<?> add(String topic) { NewTopic newTopic = new NewTopic(topic, 3, (short) 1); kafkaUtils.createTopic(Lists.newArrayList(newTopic)); return BuildResponseUtils.success(); } /** * 查询topic信息 (支持批量,这里就单个做为演示) * * @param topic 自增主键 * @return ResponseVo */ @ApiOperation("查询topic信息") @GetMapping("kafka/{topic}") public ResponseVo<String> getBytTopic(@PathVariable String topic) { return BuildResponseUtils.buildResponse(kafkaUtils.getTopicInfo(Lists.newArrayList(topic))); } /** * 删除topic (支持批量,这里就单个做为演示) * (注意:若是topic正在被监听会给人感受删除不掉(但实际上是删除掉后又会被建立)) * * @param topic topic * @return ResponseVo */ @ApiOperation("删除topic") @DeleteMapping("kafka/{topic}") public ResponseVo<?> delete(@PathVariable String topic) { kafkaUtils.deleteTopic(Lists.newArrayList(topic)); return BuildResponseUtils.success(); } /** * 查询全部topic * * @return ResponseVo */ @ApiOperation("查询全部topic") @GetMapping("kafka/allTopic") public ResponseVo<List<String>> getAllTopic() { return BuildResponseUtils.buildResponse(kafkaUtils.getAllTopic()); } /** * 生产者往topic中发送消息demo * * @param topic * @param message * @return */ @ApiOperation("往topic发送消息") @PostMapping("kafka/message") public ResponseVo<?> sendMessage(String topic, String message) { kafkaUtils.sendMessage(topic, message); return BuildResponseUtils.success(); } /** * 消费者示例demo * <p> * 基于注解监听多个topic,消费topic中消息 * (注意:若是监听的topic不存在则会自动建立) */ @KafkaListener(topics = {"topic1", "topic2", "topic3"}) public void consume(String message) { log.info("receive msg: " + message); } }