Pavel Varchenko
Pavel Varchenko

Reputation: 767

Decode ByteArray with spring 5 WebFlux framework

I'm trying to use new Spring WebFlux framework with kotlin. And I can not find where I am wrong with this code (myService):

fun foo(): Flux<ByteArray> {
    val client = WebClient.create("http://byte-array-service")
    return client
            .get()
            .uri("/info")
            .accept(MediaType.APPLICATION_OCTET_STREAM)
            .exchange()
            .flatMapMany {
                r -> r.bodyToFlux(ByteArray::class.java)
            }
}

This method returns Flux with 7893 bytes and I know there are not all bytes sent by byte-array-service. If I use old-style rest template all is ok

fun foo(): Flux<ByteArray> {
    val rt = RestTemplate()
    rt.messageConverters.add(
            ByteArrayHttpMessageConverter())
    val headers = HttpHeaders()
    headers.accept = listOf(MediaType.APPLICATION_OCTET_STREAM)

    val entity = HttpEntity<String>(headers)
    val r = rt.exchange("http://byte-array-service/info", HttpMethod.GET,entity, ByteArray::class.java)
    return Flux.just(r.body)
}

it returns all 274124 bytes sent from byte-array-service

here is my consumer

fun doReadFromByteArrayService(req: ServerRequest): Mono<ServerResponse> {

    return Mono.from(myService
            .foo()
            .flatMap {
                accepted().body(fromObject(it.size))
            })
}

Upvotes: 3

Views: 4499

Answers (1)

Alphaone
Alphaone

Reputation: 610

If I understood your question right, and you just need to deliver the flux forward, this should work. I tested it on my own environment and had no problems reading all the bytes.

To get bytes:

fun foo(): Flux<ByteArray> =
    WebClient.create("http://byte-array-service")
        .get()
        .uri("/info")
        .accept(MediaType.APPLICATION_OCTET_STREAM)
        .retrieve()
        .bodyToFlux(ByteArray::class.java)

Return bytes with response:

fun doReadFromByteArrayService(req: ServerRequest): Mono<ServerResponse> =
        ServerResponse.ok().body(foo())  

Upvotes: 1

Related Questions