10分钟带你逆袭Kafka!(13)


 
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,欢迎来撩我哦!




推荐阅读