乐闻世界logo
搜索文章和话题

How to set the event name for server sent events ( SSE ) in Quarkus

1个答案

1

In Quarkus, Server-Sent Events (SSE) can be implemented using the JAX-RS API. To configure the event name for SSE, utilize the OutboundSseEvent.Builder class to construct an event with a designated name.

Here is a simple example demonstrating how to set event names for SSE in Quarkus:

java
import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.sse.OutboundSseEvent; import javax.ws.rs.sse.Sse; import javax.ws.rs.sse.SseEventSink; import javax.enterprise.context.ApplicationScoped; @Path("/sse") @ApplicationScoped public class SseResource { @GET @Path("/stream") @Produces(MediaType.SERVER_SENT_EVENTS) public void stream(@Context SseEventSink eventSink, @Context Sse sse) { try (SseEventSink sink = eventSink) { // Create an event builder with a specific name OutboundSseEvent.Builder eventBuilder = sse.newEventBuilder(); // Build an event and set the event name to "message-event" OutboundSseEvent event = eventBuilder .name("message-event") .data(String.class, "This is a server-sent message") .build(); // Send the event sink.send(event); } } }

In this example, when a client connects to the /sse/stream endpoint, the server constructs an SSE event and sets the event name to "message-event". It then sends the constructed event to the client using eventSink.

Configuring the event name is valuable because clients can listen for events with specific names and execute different actions based on event types. In JavaScript, client-side code might appear as follows:

javascript
const evtSource = new EventSource("/sse/stream"); evtSource.addEventListener("message-event", function(event) { console.log("Received message-event: ", event.data); }); // Handle connection open event evtSource.onopen = function(event) { console.log("Connection to server opened."); }; // Handle connection error event evtSource.onerror = function(event) { console.error("EventSource failed:", event); };

In this JavaScript client-side implementation, we listen for the event named "message-event" and log the message content to the console upon receipt. Other events, such as connection open or error events, can also be handled appropriately.

2024年6月29日 12:07 回复

你的答案