|
@@ -1,7 +1,57 @@
|
|
package com.css.simulation.resource.common.controller;
|
|
package com.css.simulation.resource.common.controller;
|
|
|
|
|
|
|
|
+import org.springframework.kafka.core.KafkaTemplate;
|
|
|
|
+import org.springframework.kafka.support.SendResult;
|
|
|
|
+import org.springframework.util.concurrent.ListenableFutureCallback;
|
|
|
|
+import org.springframework.web.bind.annotation.RequestMapping;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
import org.springframework.web.bind.annotation.RestController;
|
|
|
|
|
|
|
|
+import javax.annotation.Resource;
|
|
|
|
+
|
|
@RestController
|
|
@RestController
|
|
|
|
+@RequestMapping("/kafka")
|
|
public class KafkaController {
|
|
public class KafkaController {
|
|
|
|
+
|
|
|
|
+ @Resource
|
|
|
|
+ private KafkaTemplate<String, Object> kafkaTemplate;
|
|
|
|
+
|
|
|
|
+ // -------------------------------- 简单发送 --------------------------------
|
|
|
|
+
|
|
|
|
+ @RequestMapping("/send")
|
|
|
|
+ public void sendMessage1(String normalMessage) {
|
|
|
|
+ kafkaTemplate.send("topic1",0,"key", normalMessage);
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ // -------------------------------- 带回调函数的发送 --------------------------------
|
|
|
|
+ public void sendMessage2(String callbackMessage) {
|
|
|
|
+ kafkaTemplate.send("topic1", callbackMessage).addCallback(success -> {
|
|
|
|
+ // 消息发送到的topic
|
|
|
|
+ String topic = success.getRecordMetadata().topic();
|
|
|
|
+ // 消息发送到的分区
|
|
|
|
+ int partition = success.getRecordMetadata().partition();
|
|
|
|
+ // 消息在分区内的offset
|
|
|
|
+ long offset = success.getRecordMetadata().offset();
|
|
|
|
+ System.out.println("发送消息成功:" + topic + "-" + partition + "-" + offset);
|
|
|
|
+ }, failure -> {
|
|
|
|
+ System.out.println("发送消息失败:" + failure.getMessage());
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+
|
|
|
|
+ public void sendMessage3(String callbackMessage) {
|
|
|
|
+ kafkaTemplate.send("topic1", callbackMessage).addCallback(new ListenableFutureCallback<SendResult<String, Object>>() {
|
|
|
|
+ @Override
|
|
|
|
+ public void onFailure(Throwable throwable) {
|
|
|
|
+ System.out.println("发送消息失败:" + throwable.getMessage());
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+ @Override
|
|
|
|
+ public void onSuccess(SendResult<String, Object> result) {
|
|
|
|
+ System.out.println("发送消息成功:" + result.getRecordMetadata().topic() + "-"
|
|
|
|
+ + result.getRecordMetadata().partition() + "-" + result.getRecordMetadata().offset());
|
|
|
|
+ }
|
|
|
|
+ });
|
|
|
|
+ }
|
|
|
|
+
|
|
|
|
+
|
|
}
|
|
}
|