My background: first time using Coroutines.
Context: my microservice needs call another rest endpoint. In other words, the Controller will consume another Rest Endpoint so a “normal” method will call a suspend function. Such suspend function will call another Rest Endpoint throw JDK11 HttpClient
Issues:
1 - I am confused if I am following properly how use coroutine
2 - I don’t know how handle exception in my case.
The code bellow is working (working doesn’t mean I am confident is well coded for production)
Service method as SUSPEND function calling another rest endpoint:
package com.tolearn.service
import com.tolearn.producer.DemoProducer
import io.reactivex.Single
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.net.http.HttpResponse.BodyHandlers
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Singleton
@Singleton
class DemoService {
suspend fun getCoroutine(){
val someData = getData()
print(someData)
}
suspend fun getData(): String {
val client = HttpClient.newBuilder()
.version(HttpClient.Version.HTTP_2)
.build();
val request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:3000/employees"))
.build();
val response = client.sendAsync(request, BodyHandlers.ofString());
return response.get().body() // suspend and return String not a Future
}
}
Controller
package com.tolearn.endpoint
import com.tolearn.DemoGrpcKafkaReply
import com.tolearn.DemoGrpcKafkaRequest
import com.tolearn.DemoGrpcKafkaServiceGrpc
import com.tolearn.service.DemoService
import io.grpc.stub.StreamObserver
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.*
@Singleton
class DemoEndpoint : DemoGrpcKafkaServiceGrpc.DemoGrpcKafkaServiceImplBase(){
@Inject
lateinit var demoService: DemoService
override fun send(request: DemoGrpcKafkaRequest?, responseObserver: StreamObserver<DemoGrpcKafkaReply>?) {
println(request.toString())
val tryingCoroutine = runBlocking {
coroutineScope { // Creates a coroutine scope
launch {
demoService.getCoroutine()
println("Task from nested launch")
}
}
}
println(tryingCoroutine.isCompleted)
...
}
}
Kindly, any suggestion will be appreciated.