[英]Display Kafka messages on web page
我有一個帶有Tomcat服務器的Java Spring應用程序,可以監聽kafka主題。 我想在網頁上實時顯示所有消息。 因此,當卡夫卡消息到達后端時,我想在我的網頁上看到它。 我不知道將kafka消息直接推送到前端並將其顯示在網頁上的好方法。 有人可以為我提供解決方案和一些示例嗎? 謝謝!
我沒有為Spring / Tomcat的上一個雇主在Java中實現過這樣的系統。 它正在消耗來自Kafka的消息,並在Web套接字上提供消息以在瀏覽器中顯示。 我采用的方法是使用akka-stream-kafka和akka-http獲得網絡套接字支持。 兩者的好處都是基於akka流,這使其很適合流式傳輸數據。 盡管您可以將akka-http嵌入在tomcat內運行的spring應用程序中,但它可能不再是最自然的選擇,因為spring框架已經對kafka和websockets都提供了自己的支持。 但是,如果您都不熟悉,那么采用akka方法可能是最簡單的,並且核心邏輯遵循這些原則(我無法共享工作中的代碼,因此只需將它們與文檔中的示例放在一起即可) ,未經測試):
public Route createRoute(ActorSystem system) {
return path("ws", () -> {
ConsumerSettings<byte[], String> consumerSettings = ConsumerSettings.create(system, new ByteArrayDeserializer(), new StringDeserializer())
.withBootstrapServers("localhost:9092")
.withGroupId(UUID.randomUUID().toString()) //this is so that each client gets all messages. To be able to resume from where a client left off in case of disconnects, you can generate in on the client side and pass in the request
.withProperty(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest")
return handleWebSocketMessages(
Flow.fromSinkAndSourceCoupled(
Sink.ignore(),
Consumer.committableSource(consumerSettings, Subscriptions.topics("topic1"))
.map(msg -> TextMessage.create(msg.record().value()))
)
);
}
}
要公開此路線,您可以按照簡單的示例進行操作 ,唯一的區別是您定義的路線需要ActorSystem:
final Http http = Http.get(system);
final ActorMaterializer materializer = ActorMaterializer.create(system);
final Flow<HttpRequest, HttpResponse, NotUsed> routeFlow = createRoute(system).flow(system, materializer);
final CompletionStage<ServerBinding> binding = http.bindAndHandle(routeFlow,
ConnectHttp.toHost("localhost", 8080), materializer);
將消息發布到websocket之后,前端的代碼當然將取決於您選擇的UI框架,從JavaScript消耗ws消息的最簡單代碼是:
this.connection = new WebSocket('ws://url-to-your-ws-endpoint');
this.connection.onmessage = evt => {
// display the message
為了在UI中輕松顯示消息,您希望格式方便一些,例如JSON。 如果您的Kafka消息還不是JSON,則這是第一個代碼段中的反序列化器的輸入位置,您可以在反序列化器中將其轉換為方便的JSON字符串,或者稍后在Source對象上調用.map()進行處理。
另外,如果可以選擇輪詢,那么您也可以考慮使用現成的Kafka Rest Proxy ,那么您只需要構建前端即可。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.