73 lines
2.5 KiB
Java
73 lines
2.5 KiB
Java
package com.ankurm.protocols;
|
|
|
|
import java.time.Duration;
|
|
import java.util.concurrent.atomic.AtomicLong;
|
|
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.messaging.handler.annotation.MessageMapping;
|
|
import org.springframework.stereotype.Controller;
|
|
import reactor.core.publisher.Flux;
|
|
import reactor.core.publisher.Mono;
|
|
|
|
/**
|
|
* The RSocket side. The same two operations, and one extra that exists only to make
|
|
* back-pressure visible.
|
|
*
|
|
* <p>Note what the signatures say that the other two protocols' cannot: {@code Mono} means
|
|
* request/response, {@code Flux} means request/stream, and the choice of interaction model is
|
|
* the return type rather than a separate declaration. RSocket has four (fire-and-forget,
|
|
* request/response, request/stream, channel) and Spring picks from the method shape.
|
|
*
|
|
* @see <a href="../../../../../docs/04-backpressure.md">docs/04-backpressure.md</a>
|
|
*/
|
|
@Controller
|
|
public class RSocketQuoteController {
|
|
|
|
private static final Logger log = LoggerFactory.getLogger(RSocketQuoteController.class);
|
|
|
|
/** Counts what the SERVER produced, which is the number the back-pressure test cares about. */
|
|
static final AtomicLong PRODUCED = new AtomicLong();
|
|
|
|
private final QuoteSource source;
|
|
|
|
RSocketQuoteController(QuoteSource source) {
|
|
this.source = source;
|
|
}
|
|
|
|
@MessageMapping("quote")
|
|
public Mono<Quote> quote(String symbol) {
|
|
return Mono.just(source.at(symbol, 0));
|
|
}
|
|
|
|
@MessageMapping("quotes")
|
|
public Flux<Quote> quotes(StreamSpec spec) {
|
|
Flux<Quote> flux = Flux.range(0, spec.count()).map(i -> source.at(spec.symbol(), i));
|
|
return spec.delayMs() > 0 ? flux.delayElements(Duration.ofMillis(spec.delayMs())) : flux;
|
|
}
|
|
|
|
/**
|
|
* An unbounded generator. It emits only when the transport asks, so the count it reaches is
|
|
* a direct read-out of how much the consumer requested — which is the whole argument
|
|
* for RSocket.
|
|
*/
|
|
@MessageMapping("quotes.unbounded")
|
|
public Flux<Quote> unbounded(String symbol) {
|
|
PRODUCED.set(0);
|
|
return Flux.generate(() -> 0L, (seq, sink) -> {
|
|
sink.next(source.at(symbol, seq));
|
|
PRODUCED.incrementAndGet();
|
|
return seq + 1;
|
|
});
|
|
}
|
|
|
|
@MessageMapping("produced")
|
|
public Mono<Long> produced() {
|
|
return Mono.just(PRODUCED.get());
|
|
}
|
|
|
|
/** Request payload for {@code quotes}. */
|
|
public record StreamSpec(String symbol, int count, int delayMs) {
|
|
}
|
|
}
|