Lối A · Maven
Maven 3.9+
Tải binary archive, giải nén vào thư mục ổn định, thêm thư mục
bin của Maven vào PATH, rồi kiểm tra:
mvn -versionMột JVM connector · Java và Kotlin
Chọn Maven hoặc Gradle, sau đó chọn Java hoặc Kotlin. Kotlin
là lối học chính với named arguments tường minh; Java có sample first-run
và typed deadletter dùng đúng cùng connector 3.3.2. Advanced
giữ nguyên target khi chuyển handler sang peer, File Lane, Stream Lane
và Monitor.
Beginner · 01 / 04
Bài học dùng JDK 17 làm môi trường build dễ lặp lại. Connector JVM vẫn có consumer floor Java 8, nhưng floor của package không phải là lý do để học bằng một build tool cũ. Chỉ chọn một trong hai lối dưới.
Cài JDK 17 từ một nhà cung cấp đáng tin cậy, đặt JAVA_HOME,
thêm $JAVA_HOME/bin vào PATH, rồi chạy:
java -versionLối A · Maven
Tải binary archive, giải nén vào thư mục ổn định, thêm thư mục
bin của Maven vào PATH, rồi kiểm tra:
mvn -versionLối B · Gradle
Tải binary distribution, giải nén, thêm thư mục
bin của Gradle vào PATH, rồi kiểm tra:
gradle --versionmkdir -p coakka-kotlin-demo/src/main/kotlin
cd coakka-kotlin-demopom.xml<?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>dev.coakka.learning</groupId>
<artifactId>coakka-runtime-kotlin-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<kotlin.version>2.3.10</kotlin.version>
<exec.mainClass>MainKt</exec.mainClass>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>runtime</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<version>${kotlin.version}</version>
<executions>
<execution>
<id>compile</id>
<phase>compile</phase>
<goals><goal>compile</goal></goals>
</execution>
</executions>
<configuration>
<jvmTarget>17</jvmTarget>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<mainClass>${exec.mainClass}</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
build.gradle.ktsplugins {
kotlin("jvm") version "2.3.10"
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("io.github.phuong-tran.coakka:runtime:3.3.2")
}
kotlin {
jvmToolchain(17)
}
application {
mainClass.set(
providers.gradleProperty("mainClass").orElse("MainKt"),
)
}
tasks.named<JavaExec>("run") {
standardInput = System.`in`
}
Cả hai file đều ghim đúng connector
io.github.phuong-tran.coakka:runtime:3.3.2 từ Maven Central.
Không cần clone repository hoặc tự đặt đường dẫn native library.
src/main/kotlin/Main.ktimport coakka.v2.connector.CoAkka
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val runtime = CoAkka.local(
systemName = "hello",
nodeId = "hello-1",
)
try {
runtime.handler(target = "hello.accept") { payload ->
"accepted-$payload"
}
val reply = runtime.ask(
target = "hello.accept",
payloadUtf8 = "hello",
timeoutMs = 2_000,
)
println(reply)
} finally {
runtime.shutdown()
}
}
mvn -q compile exec:javagradle runKết quả mong đợi
accepted-hello
CoAkka.local(systemName = …, nodeId = …)handler(target = …)ask(target = …, payloadUtf8 = …, timeoutMs = …)shutdown()Java dùng cùng coordinate và native Core. Tạo
src/main/java/FirstRun.java; không cần Kotlin plugin.
pom.xml<?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>dev.coakka.learning</groupId>
<artifactId>coakka-runtime-java-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<exec.mainClass>FirstRun</exec.mainClass>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>io.github.phuong-tran.coakka</groupId>
<artifactId>runtime</artifactId>
<version>3.3.2</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.6.2</version>
<configuration>
<mainClass>${exec.mainClass}</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>
build.gradle.ktsplugins {
application
}
repositories {
mavenCentral()
}
dependencies {
implementation("io.github.phuong-tran.coakka:runtime:3.3.2")
}
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
application {
mainClass.set(
providers.gradleProperty("mainClass").orElse("FirstRun"),
)
}
import coakka.v2.connector.ConnectorOrchestrator;
import coakka.v2.connector.RuntimeClient;
import coakka.v2.connector.RuntimeStartSpec;
import coakka.v2.connector.protocol.ConnectorDeliveryHint;
import java.util.Collections;
import java.util.concurrent.TimeUnit;
public final class FirstRun {
private FirstRun() {
}
public static void main(String[] args) throws Exception {
String target = "hello.accept";
RuntimeStartSpec startSpec = new RuntimeStartSpec(
"hello",
"hello-1",
Collections.singletonList(RuntimeClient.localRoute(target))
);
ConnectorOrchestrator runtime = ConnectorOrchestrator.start(startSpec);
Throwable primaryFailure = null;
try {
runtime.registerTextHandler(target, payload -> "accepted-" + payload);
String reply = runtime.getJava().askTextBlocking(
"hello-client",
target,
"hello",
2_000,
"accept",
ConnectorDeliveryHint.ROUTER_DEFAULT
);
System.out.println(reply);
} catch (Exception | Error failure) {
primaryFailure = failure;
throw failure;
} finally {
try {
runtime.getJava().shutdown().get(3, TimeUnit.SECONDS);
} catch (Exception | Error cleanup) {
if (primaryFailure == null) {
throw cleanup;
}
primaryFailure.addSuppressed(cleanup);
}
}
}
}
mvn -q compile exec:java -Dexec.mainClass=FirstRungradle run -PmainClass=FirstRunConnectorOrchestrator là Java-friendly Level 2 owner
của package JVM 3.3.2; đây không phải API bị suy đoán
từ sample cũ. getJava() trả surface dùng
CompletableFuture hoặc blocking helper.
Beginner · 02 / 04
Thay nội dung Main.kt. Target orders.quote
là địa chỉ nghiệp vụ; route chọn nơi xử lý, handler tính giá.
import coakka.v2.connector.CoAkka
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val runtime = CoAkka.local(
systemName = "orders",
nodeId = "orders-1",
)
try {
runtime.handler(target = "orders.quote") { payload ->
val quantity = payload.toInt()
"${quantity * 120_000} VND"
}
for (quantity in listOf(1, 2)) {
val quote = runtime.ask(
target = "orders.quote",
payloadUtf8 = quantity.toString(),
timeoutMs = 2_000,
)
println("quantity=$quantity quote=$quote")
}
} finally {
runtime.shutdown()
}
}
Chạy lại bằng mvn -q compile exec:java hoặc gradle run.
Kết quả mong đợi
quantity=1 quote=120000 VND quantity=2 quote=240000 VND
Thử thêm quantity 3. Bài vẫn chỉ có một process để người học tập trung vào contract trước khi thêm network.
Beginner · 03 / 04
Bài này mở API Level 2 để cố ý giữ route hợp lệ nhưng gửi tới target
không tồn tại. Package JVM 3.3.2 đặt tên owner Level 2 là
ConnectorOrchestrator; nó chỉ xuất hiện khi cần explicit
routes, outcomes hoặc effective state.
import coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.DeadletterException
import coakka.v2.connector.RuntimeClient
import coakka.v2.connector.RuntimeStartSpec
import coakka.v2.connector.TextHandler
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val runtime = ConnectorOrchestrator.start(
startSpec = RuntimeStartSpec(
systemName = "orders",
nodeId = "orders-1",
routes = RuntimeClient.localRoutes(
targets = listOf("orders.quote"),
),
),
)
try {
runtime.registerTextHandler(
target = "orders.quote",
handler = TextHandler { payload ->
"${payload.toInt() * 120_000} VND"
},
)
try {
runtime.kotlin.askText(
source = "checkout",
target = "orders.missing",
payloadUtf8 = "2",
timeoutMs = 2_000,
)
} catch (failure: DeadletterException) {
val deadletter = failure.deadletter
println(
"deadletter reason=${deadletter.reason.value} " +
"target=${deadletter.originalEnvelope?.target}",
)
}
val quote = runtime.kotlin.askText(
source = "checkout",
target = "orders.quote",
payloadUtf8 = "2",
timeoutMs = 2_000,
)
println("quantity=2 quote=$quote")
} finally {
runtime.kotlin.shutdown()
}
}
Chạy lại bằng Maven hoặc Gradle như tập 1.
Kết quả mong đợi
deadletter reason=2 target=orders.missing quantity=2 quote=240000 VND
DeadletterException.deadletter chứa reason và original
envelope do Core cấp. Không parse message text để suy đoán outcome.
Tra toàn bộ Deadletter fields và checklist.
import coakka.v2.connector.ConnectorOrchestrator;
import coakka.v2.connector.DeadletterException;
import coakka.v2.connector.RuntimeClient;
import coakka.v2.connector.RuntimeStartSpec;
import java.util.Collections;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
public final class RouteMiss {
private RouteMiss() {
}
public static void main(String[] args) throws Exception {
String liveTarget = "orders.quote";
String missingTarget = "orders.missing";
RuntimeStartSpec startSpec = new RuntimeStartSpec(
"orders",
"orders-1",
Collections.singletonList(RuntimeClient.localRoute(liveTarget))
);
ConnectorOrchestrator runtime = ConnectorOrchestrator.start(startSpec);
Throwable primaryFailure = null;
try {
runtime.registerTextHandler(
liveTarget,
quantity -> Integer.parseInt(quantity) * 120_000 + " VND"
);
try {
runtime.getJava().askText(
"checkout",
missingTarget,
"2"
).get(3, TimeUnit.SECONDS);
throw new IllegalStateException("expected route miss");
} catch (ExecutionException failure) {
if (!(failure.getCause() instanceof DeadletterException deadletterFailure)) {
throw failure;
}
System.out.println(
"deadletter reason=" + deadletterFailure.getDeadletter().getReason().getValue()
+ " target=" + missingTarget
);
}
String quote = runtime.getJava().askTextBlocking(
"checkout",
liveTarget,
"2"
);
System.out.println("quantity=2 quote=" + quote);
} catch (Exception | Error failure) {
primaryFailure = failure;
throw failure;
} finally {
try {
runtime.getJava().shutdown().get(3, TimeUnit.SECONDS);
} catch (Exception | Error cleanup) {
if (primaryFailure == null) {
throw cleanup;
}
primaryFailure.addSuppressed(cleanup);
}
}
}
}
mvn -q compile exec:java -Dexec.mainClass=RouteMissgradle run -PmainClass=RouteMissBeginner · 04 / 04
Giữ một owner theo vòng đời ứng dụng. Hàm requestQuote
là seam để HTTP endpoint, job hoặc consumer hiện có gọi CoAkka Runtime.
import coakka.v2.connector.CoAkka
import coakka.v2.connector.LocalRuntime
import kotlinx.coroutines.runBlocking
class QuoteApplication {
private val runtime: LocalRuntime = CoAkka.local(
systemName = "checkout",
nodeId = "checkout-1",
).handler(target = "orders.quote") { payload ->
"${payload.toInt() * 120_000} VND"
}
suspend fun requestQuote(quantity: Int): String = runtime.ask(
target = "orders.quote",
payloadUtf8 = quantity.toString(),
timeoutMs = 2_000,
)
suspend fun shutdown() {
runtime.shutdown()
}
}
fun main() = runBlocking {
val application = QuoteApplication()
try {
println("order quote: ${application.requestQuote(quantity = 3)}")
} finally {
application.shutdown()
}
}
Kết quả mong đợi
order quote: 360000 VND
Không tạo runtime theo từng request. Business authorization và handler thuộc app; routing, transport, bounds và outcome facts thuộc Core.
Advanced · 05
Target và caller không đổi. Quote service mở một network node trên loopback; checkout là outbound-only và route tới endpoint được công bố. Đây là distributed trực tiếp, không cần Kubernetes.
QuoteService.ktimport coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.RuntimeClient
import coakka.v2.connector.RuntimeNetworkConfig
import coakka.v2.connector.RuntimeStartSpec
import coakka.v2.connector.TextHandler
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val runtime = ConnectorOrchestrator.start(
startSpec = RuntimeStartSpec(
systemName = "pricing",
nodeId = "pricing-1",
routes = RuntimeClient.localRoutes(
targets = listOf("orders.quote"),
),
network = RuntimeNetworkConfig.networkNode(
bindHost = "127.0.0.1",
bindPort = 19_321,
advertiseHost = "127.0.0.1",
advertisePort = 19_321,
),
),
)
try {
runtime.registerTextHandler(
target = "orders.quote",
handler = TextHandler { payload ->
"${payload.toInt() * 120_000} VND"
},
)
println("quote service ready at 127.0.0.1:19321")
println("Press Enter to stop.")
readlnOrNull()
Unit
} finally {
runtime.kotlin.shutdown()
}
}
mvn -q compile exec:java -Dexec.mainClass=QuoteServiceKtgradle run -PmainClass=QuoteServiceKtChờ dòng quote service ready at 127.0.0.1:19321 và giữ terminal mở.
Checkout.ktimport coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.RuntimeEndpointFlags
import coakka.v2.connector.RuntimeEndpointSpec
import coakka.v2.connector.RuntimeNetworkConfig
import coakka.v2.connector.RuntimeRouteSpec
import coakka.v2.connector.RuntimeRouteStrategy
import coakka.v2.connector.RuntimeStartSpec
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val runtime = ConnectorOrchestrator.start(
startSpec = RuntimeStartSpec(
systemName = "checkout",
nodeId = "checkout-1",
routes = listOf(
RuntimeRouteSpec(
target = "orders.quote",
endpoints = listOf(
RuntimeEndpointSpec(
host = "127.0.0.1",
port = 19_321,
weight = 1,
flags = RuntimeEndpointFlags.NONE,
),
),
strategy = RuntimeRouteStrategy.SINGLE_OWNER,
),
),
network = RuntimeNetworkConfig.outboundOnly(),
),
)
try {
val quote = runtime.kotlin.askText(
source = "checkout",
target = "orders.quote",
payloadUtf8 = "3",
timeoutMs = 2_000,
)
println("order quote: $quote")
} finally {
runtime.kotlin.shutdown()
}
}
mvn -q compile exec:java -Dexec.mainClass=CheckoutKtgradle run -PmainClass=CheckoutKtKết quả mong đợi
order quote: 360000 VND
networkNode(bindHost = …, advertiseHost = …)outboundOnly()SINGLE_OWNERweight = 1 là route weight, không phải retry count.Advanced · 06
File Lane là data plane độc lập, dành cho file có size và SHA-256 xác định. Ví dụ tạo sender/receiver cùng process chỉ để học lifecycle.
import coakka.v2.connector.FileLane
import coakka.v2.connector.FileLaneConfig
import coakka.v2.connector.FileLaneFlags
import coakka.v2.connector.FileReceiveSpec
import coakka.v2.connector.FileTransferDirection
import coakka.v2.connector.FileTransferSnapshot
import coakka.v2.connector.LaneOwnerConfig
import java.nio.file.Files
import java.nio.file.Path
import java.util.Comparator
fun main() {
val directory = Files.createTempDirectory("coakka-file-lane-")
val source = directory.resolve("source.txt")
val destination = directory.resolve("received.txt")
Files.writeString(source, "hello from File Lane\n")
val receiver = FileLane.openOwned(
config = FileLaneConfig(
flags = FileLaneFlags.RECEIVER,
bindHost = "127.0.0.1",
bindPort = 0,
),
owner = LaneOwnerConfig(
ownerInstanceId = "receiver-1",
advertisedHost = "127.0.0.1",
),
)
val sender = FileLane.open(
config = FileLaneConfig(flags = FileLaneFlags.SENDER),
)
try {
val digest = FileLane.sha256(path = source)
val grant = receiver.prepareReceiveGrant(
spec = FileReceiveSpec(
transferId = "portal-file-1",
authorizationToken = "study-token",
destinationPath = destination,
expectedSize = digest.size,
expectedSha256 = digest.sha256,
),
)
sender.submitSend(
spec = grant.toSendSpec(
sourcePath = source,
timeoutMs = 5_000,
),
)
val sent = sender.awaitTerminal(
transferId = grant.transferId,
direction = FileTransferDirection.SEND,
)
val received = receiver.awaitTerminal(
transferId = grant.transferId,
direction = FileTransferDirection.RECEIVE,
)
check(sent.completed && received.completed)
println(Files.readString(destination).trim())
sender.forget(
transferId = grant.transferId,
direction = FileTransferDirection.SEND,
)
receiver.forget(
transferId = grant.transferId,
direction = FileTransferDirection.RECEIVE,
)
} finally {
sender.close()
receiver.close()
Files.walk(directory).use { paths ->
paths.sorted(Comparator.reverseOrder()).forEach(Files::deleteIfExists)
}
}
}
private fun FileLane.awaitTerminal(
transferId: String,
direction: FileTransferDirection,
): FileTransferSnapshot {
var afterUpdateSequence = 0L
while (true) {
val snapshot = waitTransfer(
transferId = transferId,
direction = direction,
afterUpdateSequence = afterUpdateSequence,
timeoutMs = 5_000,
)
if (snapshot.terminal) return snapshot
afterUpdateSequence = snapshot.updateSequence
}
}
mvn -q compile exec:java -Dexec.mainClass=FileLaneDemoKtgradle run -PmainClass=FileLaneDemoKtKết quả mong đợi
hello from File Lane
Production phải chuyển owner grant qua control plane đã xác thực, chờ cả SEND và RECEIVE terminal, ghi nhận outcome rồi forget record. Tra File Lane contract đầy đủ.
Advanced · 07
Stream Lane dùng callback source/consumer và bounded receive window. ByteBuffer chỉ được borrow trong callback; copy trước khi giữ lại.
import coakka.v2.connector.LaneOwnerConfig
import coakka.v2.connector.StreamConsumer
import coakka.v2.connector.StreamConsumerDecision
import coakka.v2.connector.StreamDirection
import coakka.v2.connector.StreamFrameFlags
import coakka.v2.connector.StreamLane
import coakka.v2.connector.StreamLaneConfig
import coakka.v2.connector.StreamLaneFlags
import coakka.v2.connector.StreamPublishSpec
import coakka.v2.connector.StreamSessionSnapshot
import coakka.v2.connector.StreamSource
import coakka.v2.connector.StreamSourceResult
fun main() {
val frames = listOf("frame-one", "frame-two").map(String::toByteArray)
var nextFrame = 0
val receivedFrames = mutableListOf<String>()
val publisher = StreamLane.openOwned(
config = StreamLaneConfig(
flags = StreamLaneFlags.PUBLISHER,
bindHost = "127.0.0.1",
bindPort = 0,
maxFrameBytes = 1_024,
maxWindowBytes = 4_096,
),
owner = LaneOwnerConfig(
ownerInstanceId = "publisher-1",
advertisedHost = "127.0.0.1",
),
)
val subscriber = StreamLane.open(
config = StreamLaneConfig(
flags = StreamLaneFlags.SUBSCRIBER,
maxFrameBytes = 1_024,
maxWindowBytes = 4_096,
),
)
try {
val grant = publisher.preparePublishGrant(
spec = StreamPublishSpec(
sessionId = "portal-stream-1",
authorizationToken = "study-token",
formatId = 1,
maxFrameBytes = 1_024,
source = StreamSource { destination ->
if (nextFrame == frames.size) {
StreamSourceResult.End
} else {
val frame = frames[nextFrame++]
destination.put(frame)
StreamSourceResult.Frame(
size = frame.size,
capturedMonoNs = System.nanoTime(),
flags = if (nextFrame == 1) StreamFrameFlags.KEYFRAME else 0,
)
}
},
),
)
subscriber.subscribe(
spec = grant.toSubscribeSpec(
initialWindowBytes = 4_096,
timeoutMs = 5_000,
consumer = StreamConsumer { data, _ ->
val copied = ByteArray(data.remaining())
data.get(copied)
receivedFrames += copied.toString(Charsets.UTF_8)
StreamConsumerDecision.CONTINUE
},
),
)
val published = publisher.awaitTerminal(
sessionId = grant.sessionId,
direction = StreamDirection.PUBLISH,
)
val subscribed = subscriber.awaitTerminal(
sessionId = grant.sessionId,
direction = StreamDirection.SUBSCRIBE,
)
check(published.completed && subscribed.completed)
println(receivedFrames.joinToString(separator = ", "))
publisher.forget(
sessionId = grant.sessionId,
direction = StreamDirection.PUBLISH,
)
subscriber.forget(
sessionId = grant.sessionId,
direction = StreamDirection.SUBSCRIBE,
)
} finally {
subscriber.close()
publisher.close()
}
}
private fun StreamLane.awaitTerminal(
sessionId: String,
direction: StreamDirection,
): StreamSessionSnapshot {
var afterUpdateSequence = 0L
while (true) {
val snapshot = waitSession(
sessionId = sessionId,
direction = direction,
afterUpdateSequence = afterUpdateSequence,
timeoutMs = 5_000,
)
if (snapshot.terminal) return snapshot
afterUpdateSequence = snapshot.updateSequence
}
}
mvn -q compile exec:java -Dexec.mainClass=StreamLaneDemoKtgradle run -PmainClass=StreamLaneDemoKtKết quả mong đợi
frame-one, frame-two
maxFrameBytes và initialWindowBytes là bounds,
không phải tuning trang trí. Tra flow control, pressure và failure.
Advanced · 08
Bật Monitor là startup intent. Snapshot là latest copied state;
awaitNext chờ doorbell có deadline và trả null
khi không có signal trong cửa sổ, không tự biến thành lỗi.
import coakka.v2.connector.ConnectorOrchestrator
import coakka.v2.connector.RuntimeClient
import coakka.v2.connector.RuntimeMonitorOptions
import coakka.v2.connector.RuntimeStartSpec
import coakka.v2.connector.TextHandler
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
val runtime = ConnectorOrchestrator.start(
startSpec = RuntimeStartSpec(
systemName = "orders",
nodeId = "orders-1",
routes = RuntimeClient.localRoutes(
targets = listOf("orders.quote"),
),
monitor = RuntimeMonitorOptions(enabled = true),
),
)
try {
runtime.registerTextHandler(
target = "orders.quote",
handler = TextHandler { payload ->
"${payload.toInt() * 120_000} VND"
},
)
runtime.kotlin.askText(
source = "checkout",
target = "orders.quote",
payloadUtf8 = "2",
timeoutMs = 2_000,
)
val latest = runtime.monitor.snapshot()
val next = runtime.monitor.awaitNext(timeoutMs = 250)
println("monitor enabled=${runtime.monitor.isEnabled()}")
println("latest state=${latest.health.runtimeStateName}")
println("next signal=${next?.signalCount ?: "none in 250 ms"}")
} finally {
runtime.kotlin.shutdown()
}
}
mvn -q compile exec:java -Dexec.mainClass=MonitoringKtgradle run -PmainClass=MonitoringKtMột kết quả hợp lệ
monitor enabled=true latest state=started next signal=1
Signal count có thể khác theo timing; contract cần kiểm tra là enabled, snapshot đọc được và no-signal vẫn phân biệt với closure/failure.