1、Kafka consumer和producer的配置类注释掉不需要了

2、添加kafka consumer和producer,消费者还需要做异常处理和生成指令
3、添加KafkaTopicConfig配置类,设置topic的Partition分区数
This commit is contained in:
Hao Miao
2024-01-30 00:00:39 +08:00
parent 11fb439e4c
commit 85410b9e53
7 changed files with 204 additions and 15 deletions

View File

@@ -0,0 +1,25 @@
package com.realtime.protection.server.alertmessage.kafkaConsumer;
import com.realtime.protection.configuration.entity.alert.AlertMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class KafkaProducerController {
KafkaTemplate<String, AlertMessage> kafkaTemplate;
public KafkaProducerController(KafkaTemplate<String, AlertMessage> kafkaTemplate) {
this.kafkaTemplate = kafkaTemplate;
}
@PostMapping("/kafkasend")
public void sendMessage(@RequestBody AlertMessage alerm) {
kafkaTemplate.send("topic-test", alerm);
}
}

View File

@@ -0,0 +1,24 @@
package com.realtime.protection.server.alertmessage.kafkaProducer;
import com.realtime.protection.configuration.entity.alert.AlertMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class KafkaConsumerService {
@KafkaListener(topics = "${spring.kafka.consumer.topic-name}")
public void consume(AlertMessage alerm, Acknowledgment ack) {
try {
log.info("消费者监听到数据:{}", alerm);
// 手动提交
ack.acknowledge();
} catch (Exception e) {
throw new RuntimeException("消费失败,数据: " + alerm, e);
}
}
}