springbootkafka集成(实现producer和consumer)本⽂介绍如何在springboot项⽬中集成kafka收发message。
1、先解决依赖
springboot相关的依赖我们就不提了,和kafka相关的只依赖⼀个spring-kafka集成包
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>1.1.1.RELEASE</version>
</dependency>
这⾥我们先把配置⽂件展⽰⼀下
#============== kafka ===================
kafka.producer.servers=10.93.21.21:9092
ies=0
kafka.producer.batch.size=4096
kafka.producer.linger=1
kafka.=40960
2、Configuration:Kafka producer
1)通过@Configuration、@EnableKafka,声明Config并且打开KafkaTemplate能⼒。
2)通过@Value注⼊application.properties配置⽂件中的kafka配置。
3)⽣成bean,@Bean
package com.figuration;
import java.util.HashMap;
import java.util.Map;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafkamon.serialization.StringSerializer;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.DefaultKafkaProducerFactory;
import org.KafkaTemplate;
import org.ProducerFactory;
@Configuration
@EnableKafka
public class KafkaProducerConfig {
@Value("${kafka.producer.servers}")
private String servers;
@Value("${ies}")
private int retries;
@Value("${kafka.producer.batch.size}")
private int batchSize;
@Value("${kafka.producer.linger}")
private int linger;
@Value("${kafka.}")
private int bufferMemory;
public Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
props.put(ProducerConfig.RETRIES_CONFIG, retries);
props.put(ProducerConfig.BATCH_SIZE_CONFIG, batchSize);
props.put(ProducerConfig.LINGER_MS_CONFIG, linger);
props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, bufferMemory);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}
public ProducerFactory<String, String> producerFactory() {
return new DefaultKafkaProducerFactory<>(producerConfigs());
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<String, String>(producerFactory());
}
}
实验我们的producer,写⼀个Controller。想topic=test,key=key,发送消息message package com.ller;
import com.sponse.Response;
import com.sponse.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.KafkaTemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@RestController
@RequestMapping("/kafka")
public class CollectController {
protected final Logger logger = Class());
@Autowired
private KafkaTemplate kafkaTemplate;
@RequestMapping(value = "/send", method = RequestMethod.GET)
public Response sendKafka(HttpServletRequest request, HttpServletResponse response) {
try {
String message = Parameter("message");
logger.info("kafka的消息={}", message);
kafkaTemplate.send("test", "key", message);
logger.info("发送kafka成功.");
return new Response(ResultCode.SUCCESS, "发送kafka成功", null);
} catch (Exception e) {
<("发送kafka失败", e);
return new Response(ResultCode.EXCEPTION, "发送kafka失败", null);
}
}
}
3、configuration:kafka consumer
1)通过@Configuration、@EnableKafka,声明Config并且打开KafkaTemplate能⼒。2)通过@Value注⼊application.properties配置⽂件中的kafka配置。
3)⽣成bean,@Bean
package com.figuration;
import org.apache.sumer.ConsumerConfig;
import org.apache.kafkamon.serialization.StringDeserializer;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.fig.ConcurrentKafkaListenerContainerFactory;
import org.fig.KafkaListenerContainerFactory;
import org.ConsumerFactory;
import org.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;
import java.util.HashMap;
import java.util.Map;
@Configuration
@EnableKafka
public class KafkaConsumerConfig {
@Value("${sumer.servers}")
private String servers;
@Value("${able.automit}")
private boolean enableAutoCommit;
@Value("${sumer.session.timeout}")
private String sessionTimeout;
@Value("${sumer.automit.interval}")
private String autoCommitInterval;
@Value("${up.id}")
private String groupId;
@Value("${sumer.set}")springframework和springboot
private String autoOffsetReset;
@Value("${urrency}")
private int concurrency;
@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setConcurrency(concurrency);
return factory;
}
public ConsumerFactory<String, String> consumerFactory() {
return new DefaultKafkaConsumerFactory<>(consumerConfigs());
}
public Map<String, Object> consumerConfigs() {
Map<String, Object> propsMap = new HashMap<>();
propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, servers);
propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, enableAutoCommit);
propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, autoCommitInterval);
propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, sessionTimeout);
propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, groupId);
propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, autoOffsetReset);
return propsMap;
}
@Bean
public Listener listener() {
return new Listener();
}
}
new Listener()⽣成⼀个bean⽤来处理从kafka读取的数据。Listener简单的实现demo如下:只是简单的读取并打印key和message值@KafkaListener中topics属性⽤于指定kafka topic名称,topic名称由消息⽣产者指定,也就是由kafkaTemplate在发送消息时指定。package com.figuration;
import org.apache.sumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.kafka.annotation.KafkaListener;
public class Listener {
protected final Logger logger = Class());
@KafkaListener(topics = {"test"})
public void listen(ConsumerRecord<?, ?> record) {
logger.info("kafka的key: " + record.key());
logger.info("kafka的value: " + record.value().toString());
}
}
tips:
1)我没有介绍如何安装配置kafka,配置kafka时最好⽤完全bind⽹络ip的⽅式,⽽不是localhost或者127.0.0.1
2)最好不要使⽤kafka⾃带的zookeeper部署kafka,可能导致访问不通。
3)理论上consumer读取kafka应该是通过zookeeper,但是这⾥我们⽤的是kafkaserver的地址,为什么没有深究。
4)定义监听消息配置时,GROUP_ID_CONFIG配置项的值⽤于指定消费者组的名称,如果同组中存在多个对象则只有⼀个对象能收到消息。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论