🎉 add kafka demo

This commit is contained in:
fuhou 2025-03-18 22:20:49 +08:00
parent 4f53890a10
commit 4798d5184b
2 changed files with 45 additions and 0 deletions

View File

@ -0,0 +1,19 @@
package com.darkness.engine.kafkademo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/kafka")
public class KafkaDemoController {
@Autowired
private KafkaDemoService kafkaDemoService;
@PostMapping("/demo")
public void sendMessage() {
kafkaDemoService.sendMessage("my-topic", "Hello, Kafka!");
}
}

View File

@ -0,0 +1,26 @@
package com.darkness.engine.kafkademo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class KafkaDemoService {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String topic, String message) {
kafkaTemplate.send(topic, message).addCallback(
success -> System.out.println("Message sent successfully!"),
failure -> System.err.println("Failed to send message: " + failure.getMessage())
);
}
@KafkaListener(topics = "my-topic", groupId = "darkness-group")
public void consume(String message) {
System.out.println("Received message: " + message);
}
}