Hello after migrating my http client from jetty to...
# ktor
d
Hello after migrating my http client from jetty to ktor, my service experience high cpu and high open file, any idea why this happened ? And here my code snippet, at function send async
đź‘€ 1
e
Hi @davidasync, thanks for the report. Do you close the response instance?
d
hmmm no, should i close it? because my service running overtime
e
Yep. Headers and descriptors are released only after the close.
d
is it okay to add this
clientResponse.close()
before
responseCallback.onComplete(response)
?
got this error when add that code
Copy code
I/O reactor status: STOPPED
at org.apache.http.util.Asserts.check(Asserts.java:46)
at org.apache.http.impl.nio.client.CloseableHttpAsyncClientBase.ensureRunning(CloseableHttpAsyncClientBase.java:90)
at
e
Could you check the client and responses close order?
d
Copy code
val clientResponse = httpClient!!.use { httpClient ->
          httpClient.call {
            method = requestMethod
            url(requestUrl)
            body = TextContent(requestBody, requestContentType)

            request.headers.forEach {
              if (!unsafeHeaderSet.contains(it.name)) {
                header(it.name, it.value)
              }
            }
          }.response
        }

        response.statusCode = clientResponse.status.value
        response.bodyEncoding = "UTF-8"

        clientResponse.headers.forEach { name, value ->
          val headerValue = value.joinToString(",")

          response.addHeader(name, headerValue)
        }

        clientResponse.readBytes()

        val responseBodyString = String(clientResponse.readBytes())
        response.body = IndirectNIOBuffer(ByteBuffer.wrap(responseBodyString.toByteArray(charset("UTF-8"))), true)

        responseCallback.onComplete(response)
Take a look at this code is it okay?
e
Nope. You’re trying to use the response after closing the client.
Probably you could remove
httpClient.use
and close the client on the application shutdown
d
no it cant application only triggered once, it trigger when my application shutdown
meanwhile I use httpclient to call another services
g
we had a similiar issue a few months back where we got memory leak due to the responses not being closed. Out of curiosity, is there any reason why the ktor httpClient-APIs are not using the “.use”-extension to auto close?
oops misspinged, should’ve been @e5l
e
Could you provide an example how we should auto close with
use
?
We autoclose response when the user receive custom type, but we don’t know about the response lifecycle when you use
call
or
HttpResponse
explicit.
g
cool, makes sense
d
@e5l what do you mean with
Copy code
Headers and descriptors are released only after the close.
e
When you take the
response: HttpResponse
you take the network stream with bytes inside(to consume it on demand).