使用java 语言写一个Kafka 推送数据的demo
首先,引入pom.xml
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
使用java 语言写一个Kafka 推送数据的demo,其次,建立一个生产者的service
package com.example.leetcode.kafka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class KafkaProducerService {
private static final String TOPIC = "test";
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
public void sendMessage(String message) {
kafkaTemplate.send(TOPIC, message);
}
}
第三、建立一个消费者的service
package com.example.leetcode.kafka;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Service;
@Service
public class KafkaConsumerService {
@KafkaListener(topics = "test", groupId = "kafka")
public void listen(String message) {
// 处理接收到的消息
System.out.println("Received Message: " + message);
}
}
第四、创建一个接口,调用
package com.example.leetcode.kafka.controller;
import com.example.leetcode.kafka.KafkaProducerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@Slf4j
@RestController
public class KafkaController {
@Autowired
private KafkaProducerService kafkaProducerService;
@RequestMapping("/send")
public String sendMessage(@RequestParam("message") String message) {
kafkaProducerService.sendMessage(message);
return "Message sent to Kafka: " + message;
}
@RequestMapping("test")
public String test(){
return "test";
}
}
配置一个配置文件,例如端口和kafka的一些配置
server.port=7971
spring.kafka.bootstrap-servers=127.0.0.1:9092
spring.kafka.consumer.auto-offset-reset=latest
spring.kafka.consumer.enable-auto-commit=true
spring.kafka.properties.security.protocol=SASL_PLAINTEXT
spring.kafka.properties.sasl.mechanism=PLAIN
spring.kafka.properties.sasl.jaas.config=org.apache.kafka.common.security.plain.PlainLoginModule required \
username="test" \
password="t4est@123";