我正在关注4 个低级客户端,我想调整示例以返回 CompletableFuture。我的最终目标是并行使用两个不同的端点。我是 Micronaut 的新手。我相信一种好的方法是创建两个 Micronaut 低级客户端,它们返回一个可完成的未来,然后使用 CompletableFuture.allOf().join() 加入两者
所以我将服务编码为
import com.mycomp.application.clients.EmployeClient
import com.mycomp.application.clients.EmployeeLowLevelClient
import java.awt.desktop.PrintFilesEvent
import java.util.*
import java.util.concurrent.CompletableFuture
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class EmployeeService {
@Inject
lateinit var employeClient: EmployeClient //Declarative Cliente
@Inject
lateinit var employeeLowLevelClient: EmployeeLowLevelClient //Low Level Client
fun thenCombineAsyncExample() {
val allFutures: MutableList<CompletableFuture<String>> = ArrayList<CompletableFuture<String>>()
allFutures.add(employeClient.getEmployeesA()) //### THIS WORKS
allFutures.add(employeClient.getEmployeesB()) //### THIS WORKS
employeeLowLevelClient.getEmployeeSurname()?.let { allFutures.add(it) } //### THIS FAILS
CompletableFuture.allOf(*allFutures.toTypedArray<CompletableFuture<*>>()).join()
for (i in 0..1) {
print("response: " + allFutures[i].get().toString())
}
}
}
低级客户端为
import io.micronaut.http.HttpRequest
import io.micronaut.http.client.RxHttpClient
import java.util.concurrent.CompletableFuture
import javax.inject.Singleton
@Singleton
class EmployeeLowLevelClient(private val httpClient: RxHttpClient) {
internal fun getEmployeeSurname(): CompletableFuture<String>? {
val req = HttpRequest.GET<String>("http://localhost:3000/employees_a?first_name=Jimis")
//val flowable = httpClient.retrieve(req)
return req as CompletableFuture<String> //### HERE IS THE ISSUE
}
}
例外是
java.lang.ClassCastException: class io.micronaut.http.client.netty.NettyClientHttpRequest cannot be cast to class java.util.concurrent.CompletableFuture (io.micronaut.http.client.netty.NettyClientHttpRequest is in unnamed module of loader 'app'; java.util.concurrent.CompletableFuture is in module java.base of loader 'bootstrap')
有趣的是,声明式客户端并没有例外。
import io.micronaut.http.annotation.Get
import io.micronaut.http.client.annotation.Client
import io.reactivex.Single
import java.util.concurrent.CompletableFuture
@Client()
interface EmployeClient {
@Get("http://localhost:3000/employees_a?first_name=Jimis")
fun getEmployeesA(): CompletableFuture<String>
@Get("http://localhost:3001/employees_b?first_name=Jimis")
fun getEmployeesB(): CompletableFuture<String>
}