maven 配置:
<!-- https://mvnrepository.com/artifact/org.apache.kafka/kafka-clients --> <dependency> <groupId>org.apache.kafka</groupId> <artifactId>kafka-clients</artifactId> <version>2.1.1</version> </dependency>
添加配置文件,在 Application.properties 中加入如下配置信息:
Kafka 连接地址:
spring.kafka.bootstrap-servers = 192.168.51.128:9092,10.231.128.96:9093,192.168.51.128:9094
生产者:
spring.kafka.producer.acks = 0spring.kafka.producer.key-serializer = org.apache.kafka.common.serialization.StringSerializerspring.kafka.producer.value-serializer = org.apache.kafka.common.serialization.StringSerializerspring.kafka.producer.retries = 3spring.kafka.producer.batch-size = 4096spring.kafka.producer.buffer-memory = 33554432spring.kafka.producer.compression-type = gzip
消费者:
spring.kafka.consumer.group-id = mygroupspring.kafka.consumer.auto-commit-interval = 5000spring.kafka.consumer.heartbeat-interval = 3000spring.kafka.consumer.key-deserializer = org.apache.kafka.common.serialization.StringDeserializerspring.kafka.consumer.value-deserializer = org.apache.kafka.common.serialization.StringDeserializerspring.kafka.consumer.auto-offset-reset = earliestspring.kafka.consumer.enable-auto-commit = true# listenner, 标识消费者监听的个数spring.kafka.listener.concurrency = 8# topic的名字kafka.topic1 = topic1
生产者:
import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Value;import org.springframework.kafka.core.KafkaTemplate;@Service@Slf4jpublic class MyKafkaProducerServiceImpl implements MyKafkaProducerService { @Resource private KafkaTemplate<String, String> kafkaTemplate; // 读取配置文件 @Value("${kafka.topic1}") private String topic; @Override public void sendKafka() { kafkaTemplate.send(topic, "hell world"); }}
消费者:
@Component@Slf4jpublic class MyKafkaConsumer { @KafkaListener(topics = "${kafka.topic1}") public void listen(ConsumerRecord<?, ?> record) { Optional<?> kafkaMessage = Optional.ofNullable(record.value()); if (kafkaMessage.isPresent()) { log.info("----------------- record =" + record); log.info("------------------ message =" + kafkaMessage.get());}
作者:凌晶
简介:生活中的段子手,目前就职于一家地产公司做 Devops 相关工作,曾在大型互联网公司做高级运维工程师,熟悉 linux 运维,Python 运维开发,Java 开发,Devops 常用开发组件等,个人公众号:stromling,欢迎来撩我哦!
推荐阅读
- 带你了解黑客使用的命令行浏览器,令人吃惊
- 10分钟教你Python+MySQL数据库操作
- 机架式服务器的详解,一文带你读懂
- 一文带你了解IPsec VPN基本原理与配置流程,干货值得收藏
- 带你了解香港服务器和美国服务器的区别
- 10分钟将你的Go工程转换为Go Module模式
- 带你了解太极拳的健身原理是什么
- 黄瓜|春天减肥,试试这5道“刮油菜”,10分钟端上桌,好吃解腻
- 齐刘海|素颜也好看的女生是什么样子的?女生护肤?带你get护肤小步骤!
- “疙瘩汤”的这个做法火了,10分钟出锅,好吃解馋,怎么也吃不够