我正在从VM上托管的Spring boot rest api向我的Kafka主题发送一条简单消息。当它运行时,我将得到预期的正常响应,并将该响应发送到前端,但是当kafka未运行时,它也会向前移动而不会给出异常,从而发送响应。
我已经尝试过接收响应并设置超时时间
SendResult<String, String> result=kafkaTemplate.send(kafkaTopic, message).get(5, TimeUnit.SECONDS);
logger.debug("result set returned:"+result.toString()+" also"+result.hashCode());
if (result.hashCode()>0)
return ServiceResponse.createSuccessResponse();
else {
response.setError("Server timeout error");
return response;
}
这是我完整的代码:
@CrossOrigin
@RequestMapping(value="/start", method= RequestMethod.GET, headers="Accept=application/json")
public ServiceResponse startWork(@RequestParam("message") String message) {
ServiceResponse response=null;
try {
response=new ServiceResponse();
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, kafkaURL);
props.put("acks","all");
props.put("retries", 0);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
ProducerFactory<String, String> producerFactory=new DefaultKafkaProducerFactory<>(props);
KafkaTemplate<String, String> kafkaTemplate = new KafkaTemplate<>(producerFactory);
logger.debug("Sending meesage to kafka topic :"+kafkaTopic+" url is "+kafkaURL);
SendResult<String, String> result=kafkaTemplate.send(kafkaTopic, message).get(5, TimeUnit.SECONDS);
logger.debug("result set returned:"+result.toString()+" also"+result.hashCode());
if (result.hashCode()>0)
return ServiceResponse.createSuccessResponse();
else
{
response.setError("Server timeout error");
return response;
}
} catch(Exception e) {
response.setError("Couldn't send to kafka topic");
return response;
}
}
但是每次我在前端获得成功响应时,都会出现否错误。 结果,我每次都会得到一个长的正整数。因此,如果成功阻止,那就去。