Spring boot 使用带有KakFatTemplate的send方法返回的ListenableFuture的回调时无法捕获响应
我正在使用KafkaTemplate,它提供异步发送方法,返回未来,然后向侦听器注册回调以异步接收发送结果,但如果失败,我需要捕获消息并将其存储在GCS存储桶中,但由于未知原因,我无法这样做。下面是代码片段-:Spring boot 使用带有KakFatTemplate的send方法返回的ListenableFuture的回调时无法捕获响应,spring-boot,spring-mvc,google-cloud-storage,spring-cloud,spring-kafka,Spring Boot,Spring Mvc,Google Cloud Storage,Spring Cloud,Spring Kafka,我正在使用KafkaTemplate,它提供异步发送方法,返回未来,然后向侦听器注册回调以异步接收发送结果,但如果失败,我需要捕获消息并将其存储在GCS存储桶中,但由于未知原因,我无法这样做。下面是代码片段-: public void send(String message) { ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(Topic, message); future
public void send(String message) {
ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send(Topic, message);
future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
@Override
public void onSuccess(SendResult<String, String> result) {
LOG.info("message received is : " + result.toString());
}
@Override
public void onFailure(Throwable ex) {
String dateFolder = dateFormat.format(new Date());
Storage storage = StorageOptions.getDefaultInstance().getService();
String failureFolder = failureDirectory + "/testing" + "/" + dateFolder;
String bucket = failureFolder.split("/")[2];
BlobId blobId = BlobId.of(bucket, failureFolder.split(bucket + "/")[1]);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, message.getBytes());
LOG.info("Writing to failure folder successful...");
}
});
public void发送(字符串消息){
ListenableFuture=kafkaTemplate.send(主题、消息);
future.addCallback(新ListenableFutureCallback(){
@凌驾
成功时公共无效(SendResult结果){
LOG.info(“收到的消息是:+result.toString());
}
@凌驾
失效时的公共无效(可丢弃的ex){
字符串dateFolder=dateFormat.format(newdate());
Storage Storage=StorageOptions.getDefaultInstance().getService();
字符串failureFolder=failureDirectory+“/testing”+“/”+dateFolder;
字符串bucket=failureFolder.split(“/”[2];
BlobId BlobId=BlobId.of(bucket,failureFolder.split(bucket+“/”)[1]);
BlobInfo BlobInfo=BlobInfo.newBuilder(blobId).setContentType(“text/plain”).build();
Blob Blob=storage.create(blobInfo,message.getBytes());
LOG.info(“写入失败文件夹成功…”);
}
});
}
>我不能这么做。
你什么意思?由于回调在send()
方法的作用域内,因此您可以访问message
对象-否则您的代码将无法编译。请提供更多详细信息,如您遇到的错误以及您采取的调试步骤。如果您认为该问题与谷歌云存储相关,而与代码无关,则可以在“存储和数据库”下为云存储创建一个公共问题。如果您需要共享任何特定于项目的信息,使其对公众不可见,请选择Private component,GCP支持代理之一将为您提供帮助。[1]