我正在尝试将Kafka用作我的控制器中的消息队列(所以任务):
@RequestMapping("users")
@RestController
public class UserController extends BaseController {
private static final String KAFKA_TOPIC = "virto_users";
@Autowired
private KafkaTemplate<String, String> mKafkaTemplate;
@PutMapping(value = "{id}")
public ResponseEntity<String> put(@PathVariable UUID id,
@RequestBody String profile) {
String url = ServerConfig.USERS_HOST + "/users/" + id;
ResponseEntity<String> entity = request.put(url, profile);
HttpStatus status = entity.getStatusCode();
if (status == HttpStatus.CREATED || status == HttpStatus.NO_CONTENT) {
return entity;
}
JSONObject json = new JSONObject();
json.put("id", id);
json.put("profile", profile);
sendMessage(json.toString());
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
public void sendMessage(String msg) {
mKafkaTemplate.send(KAFKA_TOPIC, msg);
}
@KafkaListener(topics = KAFKA_TOPIC, groupId = KafkaConfig.GROUP_ID)
public void listen(String message) {
JSONObject json = new JSONObject(message);
UUID id = UUID.fromString(json.getString("id"));
String profile = json.getString("profile");
put(id, profile);
}
}
如果我的内部服务可用并返回CREATED或NO_CONTENT,那么一切正确,我可以返回结果,否则我需要返回NO_CONTENT状态并将此消息放入我的队列中再次尝试直到它将被处理。我就像上面那样做了,但它看起来不是一个好的解决方案,imho。我想问一些建议,我该如何改进这个解决方案,或者它是正常的。