SpringBoot整合Kafka
配置
添加maven依赖
<!-- kafka -->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
配置application.properties/application.yml(生产者)
#spring.kafka.bootstrap-servers=
spring.kafka.bootstrap-servers=
spring.kafka.consumer.group-id=temperatureHumidityDevice
spring.kafka.auto.create.topics.enable=true
spring.kafka.consumer.auto-offset-reset=latest
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.consumer.auto-commit-interval=100
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.properties.max.poll.interval.ms=600000
spring.kafka.consumer.max-poll-records=1000
spring.kafka.topic.temperatureHumidityWarn=temperature_humidity_offline_warn
配置application.properties/application.yml(消费者)
#spring.kafka.bootstrap-servers=
spring.kafka.bootstrap-servers=
spring.kafka.consumer.group-id=videoMonitorDev
spring.kafka.auto.create.topics.enable=true
spring.kafka.consumer.auto-offset-reset=latest
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.consumer.auto-commit-interval=100
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.properties.max.poll.interval.ms=600000
spring.kafka.consumer.max-poll-records=1000
spring.kafka.topic.videoMonitor=iot_video_monitor
spring.kafka.topic.iotBioSafe=iot_bio_safe
spring.kafka.topic.offline=ambient_offline_warn
spring.kafka.topic.tem-hum-offline-data-refresh=temperature_humidity_offline_warn
!关于是producer和consumer大哥说无所谓!
消息发送类实现
@Service
public class VboxCollectionFinishMessage {
@Resource
private KafkaTemplate<String, String> kafkaTemplate;
@Value("${spring.kafka.topic.temperatureHumidityWarn}")
private String offlineTopic;
/**
*@author Administrator
*@Description
*@Date 2020/11/17
*Param
*@return
*/
public void send(){
Map<String,String> message = new HashMap<>();
message.put(UUID.randomUUID().toString(),String.valueOf(System.currentTimeMillis()));
ListenableFuture future = kafkaTemplate.send(offlineTopic,JSON.toJSONString(message));
future.addCallback(o -> System.out.println("send-消息发送成功:" + message), throwable -> System.out.println("消息发送失败:" + message));
}
}
ListenableFuture是java多线程异步调用,addCallback调用回调方法。
消息接收类实现
@Slf4j
@Component
public class TemAndHumDataRefreshListener {
@Resource
private ApplicationEventPublisher applicationEventPublisher;
@KafkaListener(topics = {"${spring.kafka.topic.tem-hum-offline-data-refresh}"}, groupId = "${spring.kafka.consumer.group-id}")
public <T> void listen(ConsumerRecord<T, String> record) {
//log.info("接收到温湿度数据刷新事件,body{}", record.value());
applicationEventPublisher.publishEvent(new DataRefreshEvent());
}
}