首页 > 解决方案 > Kotlin 中的 java.net.http.HttpClient 暂停功能:未解决的参考:等待

问题描述

我正在尝试使用 Kotlin Coroutines 对 Http Request 进行编码,如中所述

本指南其他指南

据我所见,我的代码与这两个示例都非常接近:

package com.tolearn.service

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 {

    fun postDemo(key: String, msg: String){

        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.await().body() ***here I get Unresolved reference: await
            //return response.get().body() ***this line works but I understand I should prefer use previous line with "awai()" instead of "get()"
        }
    }
}

我的最终目标是公开一个端点(控制器),它将在 Suspend 函数内调用另一个端点 throw java.net.http.HttpClient。我的微服务是完全无状态的,需要尽可能地更快、更轻。这是我第一次编写 Kotlin Coroutine。根据理论研究,我理解协程比线程便宜,我为协程做了一个很好的选择。尽管如此,我还是新手,并且正在为诸如错误/异常处理之类的疑问而苦苦挣扎,更直接地,为什么我会得到未解决的参考:等待

所以我的直接问题是:为什么 return response.await().body() 导致 Unresolved reference: await?我应该用 response.get().body() 替换吗?

任何其他建议或提示将受到高度赞赏。

*** 编辑

这是我的 build.gradle。我刚刚添加了 kotlinx-coroutines-jdk8:1.4.2

plugins {
    id("org.jetbrains.kotlin.jvm") version "1.4.10"
    id("org.jetbrains.kotlin.kapt") version "1.4.10"
    id("org.jetbrains.kotlin.plugin.allopen") version "1.4.10"
    id("com.github.johnrengelman.shadow") version "6.1.0"
    id("io.micronaut.application") version "1.2.0"
    id("com.google.protobuf") version "0.8.13"
}

version = "0.1"
group = "com.tolearn"

repositories {
    mavenLocal()
    jcenter()
    mavenCentral()
}

micronaut {
    testRuntime("junit5")
    processing {
        incremental(true)
        annotations("com.tolearn.*")
    }
}

dependencies {
    implementation("io.micronaut:micronaut-validation")
    implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}")
    implementation("org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}")
    implementation("io.micronaut.kotlin:micronaut-kotlin-runtime")
    implementation("io.micronaut:micronaut-runtime")
    implementation("io.micronaut.grpc:micronaut-grpc-runtime")
    implementation("javax.annotation:javax.annotation-api")
    implementation("io.micronaut.kafka:micronaut-kafka")

    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.2")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.4.2")

    runtimeOnly("ch.qos.logback:logback-classic")
    runtimeOnly("com.fasterxml.jackson.module:jackson-module-kotlin")
    testImplementation("io.micronaut:micronaut-http-client")
}


application {
    mainClass.set("com.tolearn.ApplicationKt")
}

java {
    sourceCompatibility = JavaVersion.toVersion("11")
}

tasks {
    compileKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }
    compileTestKotlin {
        kotlinOptions {
            jvmTarget = "11"
        }
    }


}

sourceSets {
    main {
        java {
            srcDirs("build/generated/source/proto/main/grpc")
            //srcDirs 'build/generated/source/proto/main/grpckt'
            srcDirs("build/generated/source/proto/main/java")
        }
    }
}

protobuf {
    protoc { artifact = "com.google.protobuf:protoc:3.14.0" }
    plugins {
        grpc { artifact = "io.grpc:protoc-gen-grpc-java:1.33.1" }
        //grpckt { artifact = "io.grpc:protoc-gen-grpc-kotlin:1.0.0" }
    }
    generateProtoTasks {
        all()*.plugins {
            grpc {}
            //grpckt {}
        }
    }
}

标签: kotlinkotlin-coroutinescoroutinejava-http-clientcoroutinescope

解决方案


确保您kotlinx-coroutines-jdk8的类路径中有库,然后使用以下导入语句:

import kotlinx.coroutines.future.await 

推荐阅读