欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 维修 > springboot 搭建一个 测试Kafka 集群连通性demo

springboot 搭建一个 测试Kafka 集群连通性demo

2024/11/30 6:35:15 来源:https://blog.csdn.net/qq_41865739/article/details/139733745  浏览:    关键词:springboot 搭建一个 测试Kafka 集群连通性demo

废话不多说直接上代码:
1.pom

		<!-- https://mvnrepository.com/artifact/org.springframework.kafka/spring-kafka --><dependency><groupId>org.springframework.kafka</groupId><artifactId>spring-kafka</artifactId><version>3.1.1</version></dependency>

2.配置

spring:application:name: mqdemokafka:bootstrap-servers: 10.228.48.28:39092,10.228.48.19:39092,10.228.48.21:39092consumer:group-id: my-groupauto-offset-reset: earliestproducer:key-serializer: org.apache.kafka.common.serialization.StringSerializervalue-serializer: org.apache.kafka.common.serialization.StringSerializer

3.service

package com.example.demo.service;import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;/*** @author wangjn* @Description* @createTime 2024-06-13 14:02:00*/
@Service
public class KafkaService {private final KafkaTemplate<String, String> kafkaTemplate;public KafkaService(KafkaTemplate<String, String> kafkaTemplate) {this.kafkaTemplate = kafkaTemplate;}public void sendMessage(String topic, String message) {kafkaTemplate.send(topic, message);}@KafkaListener(topics = "my-topic")public void listen(String message) {System.out.println("Received message: " + message);}
}

4.controller

package com.example.demo.web;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;/*** @author wangjn* @Description* @createTime 2024-06-13 14:08:00*/
@RestController
public class KafkaController {private static final Logger LOGGER = LoggerFactory.getLogger(KafkaController.class);@Autowiredprivate KafkaTemplate<String, String> kafkaTemplate;@PostMapping("/sendToKafka")public String sendMessageToKafka(@RequestParam("message") String message) {kafkaTemplate.send("my-topic", message);return "Message sent to Kafka successfully!";}@GetMapping("/consumeFromKafka")public String simulateConsumeFromKafka() {return "Checking for messages...";}@KafkaListener(topics = "my-topic")public void listenToKafka(String message) {LOGGER.info("Message received from Kafka: {}", message);}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com