I am trying to expose few metrics as a stream using SSE. I am able to consume the SSE event from the restController but when I added custom actuator endpoint , it just closes the connection right way.
@Component
@Endpoint(id = "test")
public class StreamMetrics {
@ReadOperation
public Flux<ServerSentEvent<String>> streamEvents() {
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> ServerSentEvent.<String> builder()
.id(String.valueOf(sequence))
.event("pingpong")
.data("ping")
.build());
}
}
Result
curl -n -v http://localhost:9080/actuator/test
* Trying ::1:9080...
* TCP_NODELAY set
* Connected to localhost (::1) port 9080 (#0)
> GET /actuator/test HTTP/1.1
> Host: localhost:9080
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< transfer-encoding: chunked
< Content-Type: text/event-stream;charset=UTF-8
<
id:0
event:pingpong
data:ping
* Connection #0 to host localhost left intact
this is terminated right after the fist event
where as
@RestController
@RequestMapping(value = "/test")
public class SSETest {
@GetMapping("/stream-sse")
public Flux<ServerSentEvent<String>> streamEvents() {
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> ServerSentEvent.<String> builder()
.id(String.valueOf(sequence))
.event("pingpong")
.data("ping")
.build());
}
}
Result
curl -v -n http://localhost:9080/test/stream-sse
* Trying ::1:9080...
* TCP_NODELAY set
* Connected to localhost (::1) port 9080 (#0)
> GET /test/stream-sse HTTP/1.1
> Host: localhost:9080
> User-Agent: curl/7.68.0
> Accept: */*
>
* Mark bundle as not supporting multiuse
< HTTP/1.1 200 OK
< transfer-encoding: chunked
< Content-Type: text/event-stream;charset=UTF-8
<
id:0
event:pingpong
data:ping
id:1
event:pingpong
data:ping
id:2
event:pingpong
data:ping
this goes on without getting terminated.
What is special about endpoint annotation that is terminating the event (continuous flow)?
I tested this in '2.2.4 ' and '2.3.0'
I found an answer. @ReadOperation(produces = "text/event-stream") will alter the default content type application/vnd.spring-boot.actuator.v3+json in actuator endpoints. There was not a document so I looked at the code.
@Component
@Endpoint(id = "test")
public class StreamMetrics {
@ReadOperation(produces = "text/event-stream")
public Flux<ServerSentEvent<String>> streamEvents() {
return Flux.interval(Duration.ofSeconds(1))
.map(sequence -> ServerSentEvent.<String> builder()
.id(String.valueOf(sequence))
.event("pingpong")
.data("ping")
.build());
}
}