Server-sent events
A method that returns EventStream<T> reads a text/event-stream response: a long-lived answer over which a service pushes updates (order statuses, prices, progress). EventStream<T> is a Stream<T> of the decoded data; the whole events, with their id, event and retry fields, are available through .events. The stream reconnects by itself, as a browser's EventSource does.
Why
Polling a service every few seconds wastes requests and still arrives late. Server-sent events push each change as it happens, over plain HTTP. Spring Cloud OpenFeign cannot stream at all; here the same client interface covers it, with reconnection built in.
Example
@FeignClient('orders', url: r'${orders.url}')
abstract interface class OrdersClient {
@GetMapping('/shops/{shop}/orders/events')
EventStream<OrderEvent> events(@PathVariable() String shop);
}
// Only the data:
await for (final order in orders.events('neon')) {
log.info(order.status);
}
// The whole events, when the id or event name matters:
orders.events('neon').events.listen((e) {
log.info('${e.id} ${e.event}: ${e.data.status}');
});
spring.feign.client.config.orders.event-stream.reconnect=true
spring.feign.client.config.orders.event-stream.reconnect-delay=3s
spring.feign.client.config.orders.event-stream.max-attempts=10
How it reads
- Each event's data is read like a JSON body, through the
ObjectMapper.EventStream<String>gives the data as sent. An event that cannot be read arrives as an error on the stream (aDecodeException), and the stream goes on. - The stream is cold: each listener opens its own connection. Cancelling the subscription (or
breakinawait for) closes it. - The request carries
Accept: text/event-stream(produceschanges it) andCache-Control: no-cache. - Interceptors run for every connection, so a refreshed token is used when the stream reconnects.
read-timeoutcovers only the wait for the response headers; after that, the stream may stay quiet as long as it likes.call-timeoutapplies to establishing each connection, not to the life of the stream.Stream<T>works as a return type too (you get anEventStream<T>).Future<EventStream<T>>is rejected at startup: return the stream directly, it connects when someone listens.
Reconnection
When the response ends or the connection breaks, the client connects again after a delay and sends the last event id in Last-Event-ID:
- a
retry:field from the server replaces the configured delay; - a
204 No Contentends the stream; - an error status ends it with the
FeignExceptionof theErrorDecoder, unless that exception is aRetryableException, which reconnects; - a stream that cannot connect within
call-timeoutfails withFeignCallTimeoutExceptionand does not reconnect; - at
logger-levelbasicand above, each reconnect is logged as---> RECONNECTING ....
| Property | Default | Meaning |
|---|---|---|
event-stream.reconnect |
true |
Connect again after the connection ended or broke. |
event-stream.reconnect-delay |
3s, or the server's retry: |
The wait before connecting again. |
event-stream.max-attempts |
no limit | How many connections in a row may end without an event before the stream gives up. |
Each under spring.feign.client.config.<name>. (or default).
Fallback
With a fallback, the fallback's stream takes over when the stream fails before its first event. Later failures reach the listener.
In tests
MockHttpTransport answers with events:
server
..when(HttpMethod.get, '/shops/neon/orders/events').respondEvents([
ServerSentEvent({'id': 1, 'status': 'NEW'}, id: '1'),
])
..when(HttpMethod.get, '/shops/neon/orders/events').respond(204); // the reconnect: stop
In Spring (Java)
Spring Cloud OpenFeign cannot stream. Spring's own answer is Flux<ServerSentEvent<OrderEvent>> (or Flux<OrderEvent>) from WebClient or an @HttpExchange interface, with reconnection left to retryWhen. Here EventStream<T> folds the event wrapper into the stream and reconnects by itself; the event-stream.* properties are additions.