如何在 Quarkus 中设置服务器发送事件 (SSE) 的事件名称
How to set the event name for server sent events (SSE) in Quarkus
我有以下 Quarkus 资源:
@Path("/myResource")
class MyResource {
@GET
@Path("/eventStream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun stream(): Multi<MyDto> = deviceStatusService.getStream()
}
这将生成没有事件名称且只有数据部分的事件。
如何指定事件名称?
根据对问题的评论,看起来它没有在 Resteasy 库中实现,一种选择是使用非反应性方法,例如
@GET
@Path("/eventStream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun stream(@Context sse: Sse, @Context sseEventSink: SseEventSink) {
return deviceStatusService.getStream().subscribe().asIterable().forEach { it -> sseEventSink.send(sse.newEvent("myEvent", it.toString()))}
}
您可以使用 OutboundSseEventImpl.BuilderImpl()
通过 json 对象构建事件。
虽然,这也是一个临时解决方案
我的最终代码现在是:
@GET
@Path("/eventStream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun stream(@Context sse: Sse, @Context sseEventSink: SseEventSink) {
deviceStatusService.getStream().subscribe().with { deviceStatus ->
sseEventSink.send(sse.newEventBuilder()
.name("deviceStatus")
.data(deviceStatus)
.build())
}
}
我有以下 Quarkus 资源:
@Path("/myResource")
class MyResource {
@GET
@Path("/eventStream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun stream(): Multi<MyDto> = deviceStatusService.getStream()
}
这将生成没有事件名称且只有数据部分的事件。 如何指定事件名称?
根据对问题的评论,看起来它没有在 Resteasy 库中实现,一种选择是使用非反应性方法,例如
@GET
@Path("/eventStream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun stream(@Context sse: Sse, @Context sseEventSink: SseEventSink) {
return deviceStatusService.getStream().subscribe().asIterable().forEach { it -> sseEventSink.send(sse.newEvent("myEvent", it.toString()))}
}
您可以使用 OutboundSseEventImpl.BuilderImpl()
通过 json 对象构建事件。
虽然,这也是一个临时解决方案
我的最终代码现在是:
@GET
@Path("/eventStream")
@Produces(MediaType.SERVER_SENT_EVENTS)
@SseElementType(MediaType.APPLICATION_JSON)
fun stream(@Context sse: Sse, @Context sseEventSink: SseEventSink) {
deviceStatusService.getStream().subscribe().with { deviceStatus ->
sseEventSink.send(sse.newEventBuilder()
.name("deviceStatus")
.data(deviceStatus)
.build())
}
}