1、Kafka consumer和producer的配置类注释掉不需要了
2、添加kafka consumer和producer,消费者还需要做异常处理和生成指令 3、添加KafkaTopicConfig配置类,设置topic的Partition分区数
This commit is contained in:
@@ -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);
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user