open
pub fn open(broker string) Client用途
打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。
参数
brokerstring- broker(string)
返回值
Client — 该类型的值
#github.com/xulang-org/packages/kafka扩展包 `kafka #github.com/xulang-org/packages/kafka`,由模块 github.com/xulang-org/packages 提供。
github.com/xulang-org/packages · 1.17.2 · 安装与使用
以下源码来自官方 examples 仓库,可复制或下载。请在完整工程中使用本地 Xu SDK 运行;网络、数据库和桌面示例需要对应的服务或资源。
33_standalone_kafka/main.xu@main
kafka #github.com/xulang-org/packages/kafka
#errors
fn verify_kafka_ping() {
println("--- 1. Testing Kafka Heartbeat & ApiVersions Ping ---")
$client := kafka.open("127.0.0.1:9092") >>> (err) {
println(" [FAIL] Connect error: " + err.msg())
<<
}
is_ok := client.ping()
if is_ok {
println(" [PASS] Kafka ApiVersions heartbeat succeeded.")
} else {
println(" [FAIL] Kafka ping failed.")
}
client.close()
}
fn verify_kafka_produce_fetch() {
println("\n--- 2. Testing Kafka Produce & Fetch Operations ---")
$client := kafka.open("127.0.0.1:9092") >>> (err) {
println(" [FAIL] Connect error: " + err.msg())
<<
}
topic := "xu_test_topic"
partition := 0
// Ensure metadata / auto create topic
client.metadata(topic + "")
// 1. Produce message
msg := "Antigravity event message from Xu language"
println(" Producing message to topic '" + topic + "': " + msg)
offset := client.produce_key_value(topic + "", partition, "event-key-1", msg + "") >>> (err) {
println(" [FAIL] Produce failed: " + err.msg())
client.close()
<<
}
println(" [PASS] Message produced successfully at offset: " + str(offset))
// 2. Fetch message back
messages := client.fetch(topic + "", partition, offset) >>> (err) {
println(" [FAIL] Fetch failed: " + err.msg())
client.close()
<<
}
println(" Fetched messages count: " + str(messages.len))
$found := false
$i := 0
while i < messages.len {
println(" Message[" + str(i) + "]: " + messages[i])
if messages[i] == msg {
found = true
}
i = i + 1
}
if found {
println(" [PASS] Produced message was verified in fetch output!")
} else {
println(" [WARN] Message not matched in first fetch chunk (may require offset adjustment).")
}
client.close()
}
fn verify_kafka_pool() {
println("\n--- 3. Testing Kafka Connection Pool ---")
$p := kafka.open_pool("127.0.0.1:9092", "xu-pool-tester", 5)
// 1. Connection Reuse Test
$c1 := p.get() >>> (err) {
println(" [FAIL] Failed to get c1: " + err.msg())
<<
}
fd1 := c1.fd
println(" Borrow 1 fd: " + str(fd1))
p.put(c1)
$c2 := p.get() >>> (err) {
println(" [FAIL] Failed to get c2: " + err.msg())
<<
}
fd2 := c2.fd
println(" Borrow 2 (after return) fd: " + str(fd2))
if fd1 == fd2 {
println(" [PASS] Connection reused successfully (fd " + str(fd1) + " == " + str(fd2) + ")")
} else {
println(" [WARN] Different fd allocated: " + str(fd1) + " vs " + str(fd2))
}
// 2. Multi-connection concurrent borrow
$c3 := p.get() >>> (err) {
println(" [FAIL] Failed to get c3: " + err.msg())
<<
}
fd3 := c3.fd
println(" Borrow 3 (concurrently) fd: " + str(fd3))
if fd2 != fd3 {
println(" [PASS] Concurrently allocated distinct fds (" + str(fd2) + " != " + str(fd3) + ")")
} else {
println(" [FAIL] Expected distinct fds for concurrent connections!")
}
p.put(c2)
p.put(c3)
// 3. Delegated Produce & Fetch via Pool
println(" Testing delegated operations via pool...")
pool_topic := "xu_pool_topic"
pool_msg := "pool message payload test"
offset := p.produce_key_value(pool_topic + "", 0, "pk1", pool_msg + "") >>> (err) {
println(" [FAIL] Pool produce failed: " + err.msg())
<<
}
println(" [PASS] Message produced via pool at offset: " + str(offset))
msgs := p.fetch(pool_topic + "", 0, offset) >>> (err) {
println(" [FAIL] Pool fetch failed: " + err.msg())
<<
}
println(" Fetched messages via pool count: " + str(msgs.len))
$found := false
$i := 0
while i < msgs.len {
if msgs[i] == pool_msg {
found = true
}
i = i + 1
}
if found {
println(" [PASS] Pool produce & fetch roundtrip verified successfully!")
} else {
println(" [WARN] Pool message not in immediate chunk.")
}
p.close()
println(" [PASS] Kafka Pool closed cleanly.")
}
fn main() {
println("=== Xu Apache Kafka Distributed Event Streaming Driver Verification ===\n")
verify_kafka_ping()
verify_kafka_produce_fetch()
verify_kafka_pool()
println("\n[KAFKA VERIFICATION 100% COMPLETED]")
}openpub fn open(broker string) Client打开资源或建立网络连接。失败时抛出错误,调用方需处理或继续传播。
broker stringClient — 该类型的值
open_clientpub fn open_client(broker string, client_id string) Client打开客户端。失败时抛出错误,调用方需处理或继续传播。
broker stringclient_id stringClient — 该类型的值
open_pool_clientpub fn open_pool_client(broker string, client_id string, max_idle int) Pool执行 open pool client 操作。
broker stringclient_id stringmax_idle intPool — 该类型的值
struct Clientpub struct Client {
pub fd int
pub broker string
pub client_id string
pub next_correlation_id int
}Kafka 客户端会话实例,维护与服务端的连接并提供操作接口。
fd intbroker stringclient_id stringnext_correlation_id int($&Client) write_exactpub fn (c $&Client) write_exact(data string) int$&Client 上的操作:执行 write exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。data stringint — 该类型的值
($&Client) read_exactpub fn (c $&Client) read_exact(n int) string$&Client 上的操作:执行 read exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。n intstring — 结果字符串
($&Client) round_trippub fn (c $&Client) round_trip(req_bytes string) string$&Client 上的操作:执行 round trip 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。req_bytes stringstring — 结果字符串
connectpub fn connect(broker string, client_id string) Client执行 connect 处理。失败时抛出错误,调用方需处理或继续传播。
broker stringclient_id stringClient — 该类型的值
($&Client) pingpub fn (c $&Client) ping() bool发送心跳保活探测请求,检测连接活性与服务可用性。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。bool — 是否成立
($&Client) metadatapub fn (c $&Client) metadata(topic string) bool在 $&Client 上执行 metadata 操作。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。topic stringbool — 是否成立
($&Client) producepub fn (c $&Client) produce(topic string, partition int, message string) int在 $&Client 上执行 produce 操作。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。topic stringpartition intmessage stringint — 该类型的值
($&Client) produce_key_valuepub fn (c $&Client) produce_key_value(topic string, partition int, key string, val string) int$&Client 上的操作:执行 produce key value 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。topic stringpartition intkey stringval stringint — 该类型的值
($&Client) fetchpub fn (c $&Client) fetch(topic string, partition int, offset int) []string在 $&Client 上执行 fetch 操作。失败时抛出错误,调用方需处理或继续传播。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。topic stringpartition intoffset int[]string — 切片结果
($&Client) closepub fn (c $&Client) close()$&Client 上的操作:关闭资源。
c $&ClientClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。不返回值。
struct Poolpub struct Pool {
pub broker string
pub client_id string
pub idle chan int
pub max_idle int
}Apache Kafka 连接池管理器,维护复用套接字连接。
broker stringclient_id stringidle chan intmax_idle intnew_poolpub fn new_pool(broker string, client_id string, max_idle int) Pool构造 pool。
broker stringclient_id stringmax_idle intPool — 该类型的值
open_poolpub fn open_pool(broker string, client_id string, max_idle int) Pool执行 open pool 操作。
broker stringclient_id stringmax_idle intPool — 该类型的值
(&Pool) getpub fn (p &Pool) get() Client在 &Pool 上执行 get 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。Client — 该类型的值
(&Pool) pingpub fn (p &Pool) ping() bool发送心跳保活探测请求,检测连接活性与服务可用性。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。bool — 是否成立
(&Pool) producepub fn (p &Pool) produce(topic string, partition int, message string) int在 &Pool 上执行 produce 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。topic stringpartition intmessage stringint — 该类型的值
(&Pool) produce_key_valuepub fn (p &Pool) produce_key_value(topic string, partition int, key string, val string) int&Pool 上的操作:执行 produce key value 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。topic stringpartition intkey stringval stringint — 该类型的值
(&Pool) fetchpub fn (p &Pool) fetch(topic string, partition int, offset int) []string在 &Pool 上执行 fetch 操作。失败时抛出错误,调用方需处理或继续传播。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。topic stringpartition intoffset int[]string — 切片结果
(&Pool) put_connpub fn (p &Pool) put_conn(fd int)&Pool 上的操作:执行 put conn 操作。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。fd int不返回值。
(&Pool) putpub fn (p &Pool) put(c Client)写入或更新指定键对应的值数据。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。c Client不返回值。
(&Pool) closepub fn (p &Pool) close()&Pool 上的操作:关闭资源。
p &PoolPool 实例;以只读借用传入,调用方仍持有实例。不返回值。
encode_i8pub fn encode_i8(v int) string编码 i8 数据。
v intstring — 结果字符串
encode_i16pub fn encode_i16(v int) string编码 i16 数据。
v intstring — 结果字符串
encode_i32pub fn encode_i32(v int) string编码 i32 数据。
v intstring — 结果字符串
encode_i64pub fn encode_i64(v int) string编码 i64 数据。
v intstring — 结果字符串
encode_stringpub fn encode_string(s string) string编码 string 数据。
s stringstring — 结果字符串
encode_null_stringpub fn encode_null_string() string编码 null string 数据。
无需传入参数。
string — 结果字符串
encode_bytespub fn encode_bytes(b string) string编码 bytes 数据。
b stringstring — 结果字符串
encode_null_bytespub fn encode_null_bytes() string编码 null bytes 数据。
无需传入参数。
string — 结果字符串
encode_zigzag_i32pub fn encode_zigzag_i32(n int) string编码 zigzag i32 数据。
n intstring — 结果字符串
encode_zigzag_i64pub fn encode_zigzag_i64(n int) string编码 zigzag i64 数据。
n intstring — 结果字符串
struct VarintResultpub struct VarintResult {
pub value int
pub bytes_read int
}承载 value、bytes_read 等属性的结构体。
value intbytes_read intdecode_varintpub fn decode_varint(s &string, off int) VarintResult解码 varint 数据。
s &stringoff intVarintResult — 该类型的值
decode_zigzagpub fn decode_zigzag(s &string, off int) VarintResult解码 zigzag 数据。
s &stringoff intVarintResult — 该类型的值
decode_i16pub fn decode_i16(s &string, off int) int解码 i16 数据。
s &stringoff intint — 该类型的值
decode_i32pub fn decode_i32(s &string, off int) int解码 i32 数据。
s &stringoff intint — 该类型的值
decode_i64pub fn decode_i64(s &string, off int) int解码 i64 数据。
s &stringoff intint — 该类型的值
build_requestpub fn build_request(api_key int, api_version int, correlation_id int, client_id string, body string) string执行 build request 操作。
api_key intapi_version intcorrelation_id intclient_id stringbody stringstring — 结果字符串
build_record_batchpub fn build_record_batch(key string, val string) string执行 build record batch 操作。
key stringval stringstring — 结果字符串
build_produce_requestpub fn build_produce_request(correlation_id int, client_id string, topic string, partition int, key string, val string) string执行 build produce request 操作。
correlation_id intclient_id stringtopic stringpartition intkey stringval stringstring — 结果字符串
build_fetch_requestpub fn build_fetch_request(correlation_id int, client_id string, topic string, partition int, offset int) string执行 build fetch request 操作。
correlation_id intclient_id stringtopic stringpartition intoffset intstring — 结果字符串
build_metadata_requestpub fn build_metadata_request(correlation_id int, client_id string, topic string) string执行 build metadata request 操作。
correlation_id intclient_id stringtopic stringstring — 结果字符串
build_apiversions_requestpub fn build_apiversions_request(correlation_id int, client_id string) string执行 build apiversions request 操作。
correlation_id intclient_id stringstring — 结果字符串
parse_produce_responsepub fn parse_produce_response(resp string) int解析为 produce response。失败时抛出错误,调用方需处理或继续传播。
resp stringint — 该类型的值
parse_fetch_responsepub fn parse_fetch_response(resp string) []string解析为 fetch response。失败时抛出错误,调用方需处理或继续传播。
resp string[]string — 切片结果
struct TlsClientpub struct TlsClient {
pub conn transport.Conn
pub host string
pub port int
}Kafka 客户端会话实例,维护与服务端的连接并提供操作接口。
conn transport.Connhost stringport inttls_connectpub fn tls_connect(endpoint string, default_port int) TlsClient执行 tls connect 操作。失败时抛出错误,调用方需处理或继续传播。
endpoint stringdefault_port intTlsClient — 该类型的值
tls_connect_configpub fn tls_connect_config(endpoint string, default_port int, cfg tls.Config) TlsClient执行 tls connect config 操作。失败时抛出错误,调用方需处理或继续传播。
endpoint stringdefault_port intcfg tls.ConfigTlsClient — 该类型的值
($&TlsClient) write_allpub fn (c $&TlsClient) write_all(data string) int$&TlsClient 上的操作:执行 write all 操作。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。data stringint — 该类型的值
($&TlsClient) readpub fn (c $&TlsClient) read(max int) string$&TlsClient 上的操作:读出最多 max 字节。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。max intstring — 结果字符串
($&TlsClient) read_exactpub fn (c $&TlsClient) read_exact(need int) string$&TlsClient 上的操作:执行 read exact 操作。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。need intstring — 结果字符串
($&TlsClient) closepub fn (c $&TlsClient) close() int$&TlsClient 上的操作:关闭资源。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。int — 该类型的值
($&TlsClient) set_deadlinepub fn (c $&TlsClient) set_deadline(t_ns int) int$&TlsClient 上的操作:设置 deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值
($&TlsClient) set_read_deadlinepub fn (c $&TlsClient) set_read_deadline(t_ns int) int$&TlsClient 上的操作:设置 read deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值
($&TlsClient) set_write_deadlinepub fn (c $&TlsClient) set_write_deadline(t_ns int) int$&TlsClient 上的操作:设置 write deadline。失败时抛出错误,调用方需处理或继续传播。
c $&TlsClientTlsClient 实例;以独占借用传入,方法可修改它,调用方仍持有实例。t_ns intint — 该类型的值