Học với Kotlin + Java · gói 2.3.2
Ưu tiên Kotlin, hỗ trợ Java trên cùng một JVM connector
Ví dụ Kotlin dùng tham số có tên để làm rõ ý nghĩa. Ví dụ Java dùng lambda, getter và overload tường minh. Cả hai cùng sử dụng một JAR, một gói native phù hợp với nền tảng và một contract của CoAkka HTTP Runtime.
Beginner · 01 / 04
Cài từ Maven Central
Dùng JDK 17 để biên dịch và chạy bài học. JAR được phát hành dưới dạng Java 8 bytecode để tương thích rộng, nhưng môi trường học vẫn nên dùng JDK 17. Chọn Maven hoặc Gradle; không cần clone GitHub hay tải JAR thủ công.
Maven và Gradle cùng tải JAR của JVM connector và gói native đúng nền tảng ở phiên bản 2.3.2 từ Maven Central.
io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2
MavenDùng pom.xml; phù hợp với dự án Maven và IDE hỗ trợ Maven.
Kiểm tra JDK 17 và Maven 3.9+, sau đó sao chép cấu hình POM vào dự án.
java --version
mvn --version<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>example.coakka</groupId>
<artifactId>coakka-http-jvm-study</artifactId>
<version>1.0.0</version>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.release>8</maven.compiler.release>
<kotlin.version>2.3.10</kotlin.version>
<coakka.version>2.3.2</coakka.version>
<coakka.target>macos-aarch64</coakka.target>
</properties>
<dependencies>
<dependency>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>coakka-http-runtime-jvm</artifactId>
<version>${coakka.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile-kotlin</id>
<phase>process-sources</phase>
<goals><goal>compile</goal></goals>
<configuration>
<jvmTarget>1.8</jvmTarget>
<args><arg>-Werror</arg><arg>-Xjdk-release=8</arg></args>
<sourceDirs>
<sourceDir>${project.basedir}/src/main/kotlin</sourceDir>
</sourceDirs>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<release>8</release>
<showWarnings>true</showWarnings>
<compilerArgs><arg>-Xlint:all</arg><arg>-Werror</arg></compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.8.1</version>
<executions>
<execution>
<id>unpack-coakka-native</id>
<phase>process-resources</phase>
<goals><goal>unpack</goal></goals>
<configuration>
<artifactItems>
<artifactItem>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>coakka-http-runtime-jvm</artifactId>
<version>${coakka.version}</version>
<classifier>${coakka.target}</classifier>
<type>zip</type>
<outputDirectory>${project.build.directory}/coakka-native</outputDirectory>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Gradle Kotlin DSLDùng build.gradle.kts; tạo Wrapper một lần rồi chạy bằng Wrapper.
Kiểm tra JDK 17 và Gradle, tạo Wrapper 9.2.1, rồi từ đó dùng ./gradlew hoặc gradlew.bat.
java --version
gradle --version
gradle wrapper --gradle-version 9.2.1plugins {
kotlin("jvm") version "2.3.10"
application
}
repositories {
mavenCentral()
}
val coakkaTarget = providers.gradleProperty("coakkaTarget")
.orElse("macos-aarch64")
val coakkaNative by configurations.creating
dependencies {
implementation("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2")
coakkaNative("io.github.phuong-tran.coakka:coakka-http-runtime-jvm:2.3.2:${coakkaTarget.get()}@zip")
}
val unpackCoakkaNative by tasks.registering(Sync::class) {
from(coakkaNative.map(::zipTree))
into(layout.buildDirectory.dir("coakka-native"))
}
kotlin {
jvmToolchain(17)
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_1_8)
freeCompilerArgs.add("-Xjdk-release=8")
allWarningsAsErrors.set(true)
}
}
java {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.withType<JavaCompile>().configureEach {
options.release.set(8)
options.compilerArgs.addAll(listOf("-Xlint:all", "-Werror"))
}
application {
mainClass.set("study.KotlinMainKt")
}
tasks.withType<JavaExec>().configureEach {
dependsOn(unpackCoakkaNative)
standardInput = System.`in`
jvmArgs("-Djava.library.path=" +
layout.buildDirectory.dir("coakka-native/native").get().asFile.absolutePath)
}
tasks.register<JavaExec>("runJava") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.JavaMain")
}
tasks.register<JavaExec>("runKotlinAdvanced") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.KotlinAdvancedKt")
}
tasks.register<JavaExec>("runJavaAdvanced") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.JavaAdvanced")
}
tasks.register<JavaExec>("runKotlinFile") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.KotlinFileKt")
}
tasks.register<JavaExec>("runKotlinSse") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.KotlinSseKt")
}
tasks.register<JavaExec>("runKotlinWebSocket") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.KotlinWebSocketKt")
}
tasks.register<JavaExec>("runJavaFile") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.JavaFile")
}
tasks.register<JavaExec>("runJavaSse") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.JavaSse")
}
tasks.register<JavaExec>("runJavaWebSocket") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.JavaWebSocket")
}
tasks.register<JavaExec>("runKotlinOutbound") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.KotlinOutboundKt")
}
tasks.register<JavaExec>("runJavaOutbound") {
group = "application"
classpath = sourceSets.main.get().runtimeClasspath
mainClass.set("study.JavaOutbound")
}
Chọn gói native theo nền tảngChỉ cần mở khi phải đổi hệ điều hành hoặc kiến trúc CPU mặc định.
- macOS Apple Silicon
macos-aarch64- Linux ARM64 / Raspberry Pi
linux-aarch64- Linux x86-64 / WSL2 x86-64
linux-x86_64- Windows ARM64
windows-aarch64- Windows x86-64
windows-x86_64java.library.path- Trỏ tới thư mục
native/đã giải nén, không trỏ tới tệp ZIP hoặc thư mục cha. - Kotlin stdlib
- Phiên bản 2.3.10 được kéo theo tự động. Dự án chỉ viết Java vẫn cần thư viện này vì connector được viết bằng Kotlin.
ConnectorOrchestrator.Bài học dùng API công khai ServiceBuilder/Service 2.3.2. Tên cũ này không còn thuộc API hiện hành.
Beginner · 02 / 04
Chạy Kotlin service đầu tiên
Lưu file dưới vào src/main/kotlin/study/KotlinMain.kt:
package study
import coakka.http.Handler
import coakka.http.Responses
import coakka.http.ServiceBuilder
fun main() {
val service = ServiceBuilder()
.listen("127.0.0.1", 0)
.get("/hello/{name}", Handler { request ->
val name = request.pathParameters.first().encodedValue()
.toString(Charsets.UTF_8)
Responses.text("hello $name", status = 200)
})
.start()
service.use {
println("http://127.0.0.1:${it.port}/hello/Ada")
println("Press Enter to close")
readlnOrNull()
}
}
Chạy bằng MavenBuild, resolve classpath và chạy Kotlin main trên POSIX.
mvn -Dcoakka.target=macos-aarch64 clean package \
dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinMainKtChạy bằng GradleDùng Wrapper đã tạo ở tập 01.
./gradlew run -PcoakkaTarget=macos-aarch64Dùng URL do chương trình in ra: curl -i http://127.0.0.1:49321/hello/Ada → 200 hello Ada. Sau đó nhấn Enter để đóng dịch vụ.
Beginner · 03 / 04
Đọc request và dùng tham số có tên
val name = request.pathParameters.first().encodedValue()
.toString(Charsets.UTF_8)
Responses.text("hello $name", status = 200)
pathParameters- Giữ thứ tự của route.
encodedValue()vẫn là dữ liệu đã mã hóa; ứng dụng quyết định cách giải mã và kiểm tra. status = 200- Tham số có tên làm rõ ý nghĩa. Nên ưu tiên cách viết này trong Kotlin khi API công bố tên tham số.
request.bytes()- Đọc toàn bộ body trong giới hạn đã cấu hình. Upload lớn dùng
postStream. Headers- Tên header không phân biệt chữ hoa, chữ thường; thứ tự và giá trị trùng lặp vẫn được giữ lại.
JNI adapter đã sao chép các giá trị của request sang JVM; con trỏ native mượn tạm không thoát khỏi ranh giới này. Ứng dụng vẫn tự chọn JSON hoặc codec cho dữ liệu nghiệp vụ.
Beginner · 04 / 04
Java dùng cùng gói, không cần viết Kotlin
Lưu file thành src/main/java/study/JavaMain.java:
package study;
import coakka.http.Responses;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import java.nio.charset.StandardCharsets;
public final class JavaMain {
private JavaMain() {}
public static void main(String[] args) throws Exception {
Service service = new ServiceBuilder()
.listen("127.0.0.1", 0)
.get("/hello/{name}", request -> Responses.text(
"hello " + new String(
request.getPathParameters().get(0).encodedValue(),
StandardCharsets.UTF_8),
200))
.start();
try {
System.out.printf("http://127.0.0.1:%d/hello/Ada%n", service.getPort());
System.out.println("Press Enter to close");
System.in.read();
} finally {
service.close();
}
}
}
Chạy bằng MavenCùng POM và native classifier đã chọn.
mvn -Dcoakka.target=macos-aarch64 clean package \
dependency:build-classpath -Dmdep.outputFile=target/classpath.txt
java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaMainChạy bằng GradleDùng task runJava trong build đã copy.
./gradlew runJava -PcoakkaTarget=macos-aarch64Java dùng overload tường minh Responses.text(body, status), getter và lambda. Khối finally giúp lỗi khi đóng dịch vụ không bị bỏ qua và giữ đối tượng dịch vụ còn sống cho tới khi quá trình đóng kết thúc.
Advanced · 05
Học từng capability trước khi kết hợp
Bắt đầu bằng một service chỉ làm một việc. Chọn Kotlin hoặc Java trong từng chủ đề; cả hai dùng cùng artifact Maven Central 2.3.2 và native classifier đã cài ở tập 1.
01 · File deliveryAuthority, relative path và limit; CoAkka HTTP Runtime tự chọn sendfile khi đủ điều kiện.
KotlinNamed parameter làm rõ từng giới hạn.
package study
import coakka.http.FileAuthority
import coakka.http.Handler
import coakka.http.Responses
import coakka.http.ServiceBuilder
import java.nio.file.Files
fun main() {
val root = Files.createTempDirectory("coakka-http-file-")
val manual = root.resolve("manual.txt")
Files.write(manual, "CoAkka file delivery\n".toByteArray())
val service = ServiceBuilder()
.listen(host = "127.0.0.1", port = 0)
.fileAuthority(
FileAuthority(
id = 1,
rootPath = root.toString(),
maxActiveFiles = 4,
maxFileBytes = 1_024,
),
)
.get("/download", Handler {
Responses.file(authorityId = 1, encodedPath = "/manual.txt")
})
.start()
try {
println("curl http://127.0.0.1:${service.port}/download")
println("Press Enter to close")
readlnOrNull()
} finally {
service.close()
Files.deleteIfExists(manual)
Files.deleteIfExists(root)
}
}
./gradlew runKotlinFile -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinFileKtJavaCùng file-response contract bằng Java API.
package study;
import coakka.http.FileAuthority;
import coakka.http.Responses;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public final class JavaFile {
private JavaFile() {}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("coakka-http-file-");
Path manual = root.resolve("manual.txt");
Files.write(manual, "CoAkka file delivery\n".getBytes(StandardCharsets.UTF_8));
Service service = new ServiceBuilder()
.listen("127.0.0.1", 0)
.fileAuthority(new FileAuthority(1L, root.toString(), 4, 1024))
.get("/download", request -> Responses.file(1L, "/manual.txt"))
.start();
try {
System.out.printf("curl http://127.0.0.1:%d/download%n", service.getPort());
System.out.println("Press Enter to close");
System.in.read();
} finally {
service.close();
Files.deleteIfExists(manual);
Files.deleteIfExists(root);
}
}
}
./gradlew runJavaFile -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaFile02 · Server-Sent EventsMột response stream một chiều với data, event, id và retry.
KotlinPhát hai event rồi kết thúc stream.
package study
import coakka.http.Handler
import coakka.http.Responses
import coakka.http.ServerSentEvent
import coakka.http.ServerSentEventsProducer
import coakka.http.ServiceBuilder
fun main() {
val events = Responses.serverSentEvents(
producer = ServerSentEventsProducer { writer ->
writer.write(
ServerSentEvent(
data = "ready".toByteArray(),
eventType = "state",
id = "1",
retryMillis = 1_000,
),
)
writer.write(ServerSentEvent(data = "done".toByteArray()))
},
)
val service = ServiceBuilder()
.listen(host = "127.0.0.1", port = 0)
.get("/events", Handler { events })
.start()
try {
println("curl -N http://127.0.0.1:${service.port}/events")
println("Press Enter to close")
readlnOrNull()
} finally {
service.close()
}
}
./gradlew runKotlinSse -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinSseKtJavaCùng event fields bằng Java constructors.
package study;
import coakka.http.Responses;
import coakka.http.ServerSentEvent;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import java.nio.charset.StandardCharsets;
public final class JavaSse {
private JavaSse() {}
public static void main(String[] args) throws Exception {
Service service = new ServiceBuilder()
.listen("127.0.0.1", 0)
.get("/events", request -> Responses.serverSentEvents(writer -> {
writer.write(new ServerSentEvent(
"ready".getBytes(StandardCharsets.UTF_8), "state", "1", 1000L));
writer.write(new ServerSentEvent(
"done".getBytes(StandardCharsets.UTF_8)));
}))
.start();
try {
System.out.printf("curl -N http://127.0.0.1:%d/events%n", service.getPort());
System.out.println("Press Enter to close");
System.in.read();
} finally {
service.close();
}
}
}
./gradlew runJavaSse -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaSse03 · WebSocketUpgrade với subprotocol, greeting và text echo hai chiều.
KotlinXử lý OPEN và TEXT riêng.
package study
import coakka.http.Handler
import coakka.http.Responses
import coakka.http.ServiceBuilder
import coakka.http.ServiceWebSocketHandler
import coakka.http.WebSocketEventKind
fun main() {
val socket = Responses.webSocket(
handler = ServiceWebSocketHandler { session, event ->
when (event.kind) {
WebSocketEventKind.OPEN -> session.sendText("ready")
WebSocketEventKind.TEXT -> {
val message = event.bytes().toString(Charsets.UTF_8)
session.sendText("echo: $message")
}
else -> Unit
}
},
subprotocol = "coakka.demo",
)
val service = ServiceBuilder()
.listen(host = "127.0.0.1", port = 0)
.webSocket("/socket", Handler { socket })
.start()
try {
println(
"new WebSocket('ws://127.0.0.1:${service.port}/socket', 'coakka.demo')",
)
println("Press Enter to close")
readlnOrNull()
} finally {
service.close()
}
}
./gradlew runKotlinWebSocket -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinWebSocketKtJavaCùng session lifecycle bằng Java API.
package study;
import coakka.http.Responses;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import coakka.http.WebSocketEventKind;
import java.nio.charset.StandardCharsets;
public final class JavaWebSocket {
private JavaWebSocket() {}
public static void main(String[] args) throws Exception {
Service service = new ServiceBuilder()
.listen("127.0.0.1", 0)
.webSocket("/socket", request -> Responses.webSocket((session, event) -> {
if (event.getKind() == WebSocketEventKind.OPEN) {
session.sendText("ready");
} else if (event.getKind() == WebSocketEventKind.TEXT) {
String message = new String(event.bytes(), StandardCharsets.UTF_8);
session.sendText("echo: " + message);
}
}, "coakka.demo"))
.start();
try {
System.out.printf(
"new WebSocket('ws://127.0.0.1:%d/socket', 'coakka.demo')%n",
service.getPort());
System.out.println("Press Enter to close");
System.in.read();
} finally {
service.close();
}
}
}
./gradlew runJavaWebSocket -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaWebSocket04 · Kết hợp trong một serviceBài tích hợp tùy chọn sau khi ba contract riêng đã rõ.
KotlinBa endpoint, một service owner.
package study
import coakka.http.FileAuthority
import coakka.http.Handler
import coakka.http.Responses
import coakka.http.ServerSentEvent
import coakka.http.ServerSentEventsProducer
import coakka.http.ServiceBuilder
import coakka.http.ServiceWebSocketHandler
import coakka.http.WebSocketEventKind
import java.nio.file.Files
private const val fileAuthorityId = 1L
fun main() {
val root = Files.createTempDirectory("coakka-http-advanced-")
val manual = root.resolve("manual.txt")
Files.write(manual, "CoAkka file delivery\n".toByteArray())
val events = Responses.serverSentEvents(
producer = ServerSentEventsProducer { writer ->
writer.write(
ServerSentEvent(
data = "ready".toByteArray(),
eventType = "state",
id = "1",
retryMillis = 1_000,
),
)
writer.write(ServerSentEvent(data = "done".toByteArray()))
},
)
val socket = Responses.webSocket(
handler = ServiceWebSocketHandler { session, event ->
when (event.kind) {
WebSocketEventKind.OPEN -> session.sendText("ready")
WebSocketEventKind.TEXT -> {
val message = event.bytes().toString(Charsets.UTF_8)
session.sendText("echo: $message")
}
else -> Unit
}
},
subprotocol = "coakka.demo",
)
val service = ServiceBuilder()
.listen(host = "127.0.0.1", port = 0)
.fileAuthority(
FileAuthority(
id = fileAuthorityId,
rootPath = root.toString(),
maxActiveFiles = 4,
maxFileBytes = 1_024,
),
)
.get("/download", Handler {
Responses.file(
authorityId = fileAuthorityId,
encodedPath = "/manual.txt",
)
})
.get("/events", Handler { events })
.webSocket("/socket", Handler { socket })
.start()
try {
println("file: curl http://127.0.0.1:${service.port}/download")
println("SSE: curl -N http://127.0.0.1:${service.port}/events")
println(
"WS: new WebSocket('ws://127.0.0.1:${service.port}/socket', 'coakka.demo')",
)
println("Press Enter to close")
readlnOrNull()
} finally {
service.close()
Files.deleteIfExists(manual)
Files.deleteIfExists(root)
}
}
./gradlew runKotlinAdvanced -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.KotlinAdvancedKtJavaBa endpoint bằng Java API.
package study;
import coakka.http.FileAuthority;
import coakka.http.Responses;
import coakka.http.ServerSentEvent;
import coakka.http.Service;
import coakka.http.ServiceBuilder;
import coakka.http.WebSocketEventKind;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public final class JavaAdvanced {
private static final long FILE_AUTHORITY_ID = 1L;
private JavaAdvanced() {}
public static void main(String[] args) throws Exception {
Path root = Files.createTempDirectory("coakka-http-advanced-");
Path manual = root.resolve("manual.txt");
Files.write(manual, "CoAkka file delivery\n".getBytes(StandardCharsets.UTF_8));
Service service = new ServiceBuilder()
.listen("127.0.0.1", 0)
.fileAuthority(new FileAuthority(FILE_AUTHORITY_ID, root.toString(), 4, 1024))
.get("/download", request ->
Responses.file(FILE_AUTHORITY_ID, "/manual.txt"))
.get("/events", request -> Responses.serverSentEvents(writer -> {
writer.write(new ServerSentEvent(
"ready".getBytes(StandardCharsets.UTF_8), "state", "1", 1000L));
writer.write(new ServerSentEvent(
"done".getBytes(StandardCharsets.UTF_8)));
}))
.webSocket("/socket", request -> Responses.webSocket((session, event) -> {
if (event.getKind() == WebSocketEventKind.OPEN) {
session.sendText("ready");
} else if (event.getKind() == WebSocketEventKind.TEXT) {
String message = new String(event.bytes(), StandardCharsets.UTF_8);
session.sendText("echo: " + message);
}
}, "coakka.demo"))
.start();
try {
System.out.printf("file: curl http://127.0.0.1:%d/download%n", service.getPort());
System.out.printf("SSE: curl -N http://127.0.0.1:%d/events%n", service.getPort());
System.out.printf(
"WS: new WebSocket('ws://127.0.0.1:%d/socket', 'coakka.demo')%n",
service.getPort());
System.out.println("Press Enter to close");
System.in.read();
} finally {
service.close();
Files.deleteIfExists(manual);
Files.deleteIfExists(root);
}
}
}
./gradlew runJavaAdvanced -PcoakkaTarget=macos-aarch64java -Djava.library.path=target/coakka-native/native \
-cp "target/classes:$(cat target/classpath.txt)" study.JavaAdvancedTra cứu toàn bộ tính năng · Thử gzip · Chạy bài upload · Tiếp tục tải tệp lớn lên
Advanced · 06
Đọc đúng kết quả của outbound và điều khiển khi đang chạy
| Công việc | API JVM | Điều phải giữ đúng |
|---|---|---|
| Gọi HTTP ra ngoài | submitOutbound, takeOutbound | Khớp đúng mã lời gọi; lý do, giai đoạn, khả năng thử lại và độ chắc chắn tách biệt với HTTP status. |
| Đọc ảnh chụp route | service.routes / getRoutes() | Dùng trạng thái nhất quán do Core cấp, không suy từ khai báo cục bộ. |
| Đổi handler | prepareHandler, rebindHandler | So khớp generation và revision; request đã nhận vẫn dùng handler cũ. |
| Công bố route | Công bố toàn bộ cấu trúc route | Mỗi lần công bố là một generation hoàn chỉnh, không vá từng phần. |
Advanced · 07
Đọc trạng thái thực tế và tích hợp với framework
runtimeInfo()- Thông tin về protocol, provider và capability đã được Core chấp nhận.
effectiveLimits()- Các giới hạn đang có hiệu lực, không phải bản sao của dữ liệu đưa vào builder.
- Health/liveness
- Có thể đọc health và chạy phép kiểm tra liveness hữu hạn mà không cần bật Monitor.
- Monitor
- Đặt trước dung lượng khi khởi động; thay đổi policy theo generation; event, snapshot và thông tin mất dữ liệu đều có giới hạn.
- Spring Boot/Quarkus
- Framework sở hữu DI, cấu hình và vòng đời ứng dụng. Adapter tạo và đóng đúng một
Service, không thay đổi contract của Core.
Health, liveness và Monitor · Đóng dịch vụ trong thời gian hữu hạn
Advanced · 08
Xử lý lỗi, đóng dịch vụ và tra cứu nhanh
- Khởi động
- Mỗi
ServiceBuilderchỉ dùng một lần. Provider không hỗ trợ hoặc cấu hình không hợp lệ trả về lỗi có kiểu; dịch vụ không chuyển sang trạng thái sẵn sàng một phần. - Handler/stream
- Lỗi bất đồng bộ đi vào hàng đợi lỗi hữu hạn của dịch vụ; đọc bằng
pollError(). - API cấp thấp
- Dùng
HttpRuntimeExceptionvàResultCodecó kiểu; không phân tích chuỗi thông báo lỗi. - Đóng dịch vụ
Servicetriển khaiAutoCloseable. Timeout và interruption phải quan sát được; nếu đóng chưa xong thì vẫn giữ đối tượng dịch vụ để xử lý tiếp.- Bằng chứng
- Ghi hash của JAR và ZIP native, đường dẫn đã nạp, hệ điều hành và kiến trúc của JVM, runtime info, giới hạn thực tế, workload và kết quả cuối.
- JAR và gói native cùng phiên bản 2.3.2.
- Gói native khớp với tiến trình JVM, không chỉ khớp hệ điều hành của máy.
- Kotlin ưu tiên tham số có tên; Java dùng overload công khai, không gọi hàm mặc định do trình biên dịch sinh ra.
- Mỗi lane cấp thấp chỉ có một bộ đọc.
- Không bỏ đối tượng dịch vụ khi quá trình đóng chưa hoàn tất.