Java SDK
服务端埋点,语义与 Go SDK 相同,两种后端可以抄同一套调用方式。Java 17 及以上,除 JDK 外没有第三方依赖,HTTP 用 java.net.http.HttpClient。
安装
Maven:
xml
<dependency>
<groupId>cc.mosong.evstats</groupId>
<artifactId>evstats-sdk</artifactId>
<version>X.Y.Z</version>
</dependency>Gradle:
groovy
implementation "cc.mosong.evstats:evstats-sdk:X.Y.Z"包名 cc.mosong.evstats.sdk,发布在 Maven Central,版本标签是 sdk-java/vX.Y.Z。
用法
java
import cc.mosong.evstats.sdk.Event;
import cc.mosong.evstats.sdk.EvstatsClient;
try (EvstatsClient client = EvstatsClient.builder()
.endpoint("https://stats.example.com/sa")
.key(System.getenv("EVSTATS_KEY")) // evs_wk_xxx
.build()) {
client.track(Event.builder()
.distinctId("user_42")
.event("order_paid")
.property("amount", 99)
.property("plan", "pro")
.build());
}EvstatsClient 实现 AutoCloseable。close() 刷完队列,默认最多等 3 秒,之后不再接收事件。
Event
| 方法 | 规则 |
|---|---|
distinctId(String) | 必填,映射规则与 Go 相同:写进 anonymousId |
userId(String) | 可选,写进 userId |
event(String) | 必填 |
time(Instant) | 为空时用 Instant.now() |
property(key, value) | 值是字符串、数字或布尔;也可以 properties(Map) 一次放多个 |
其它方法
| 方法 | 发送 |
|---|---|
identify(distinctId, userId) / identify(distinctId, userId, traits) | type=identify |
profile(distinctId, properties) | profile_set |
profileSetOnce(distinctId, properties) | profile_set_once |
profileIncrement(distinctId, properties) | profile_increment |
flush() | 立即发送队列 |
close() | 发完队列后停止 |
Builder
| 方法 | 默认 | 说明 |
|---|---|---|
endpoint(String) | 必填 | 完整采集地址 |
key(String) | 必填 | 写入密钥 |
flushInterval(Duration) | 500ms | 发送间隔 |
batchSize(int) | 100 | 单批条数 |
queueSize(int) | 1000 | 内存队列长度 |
dropPolicy(DropPolicy) | DROP_OLDEST | RETURN_ERROR 时队列满则 track 抛出 EvstatsQueueFullException |
httpClient(HttpClient) | 新建的 HTTP/1.1 客户端 | 自定义客户端 |
timeout(Duration) | 5 秒 | 单次请求超时 |
closeTimeout(Duration) | 3 秒 | close 最多等多久 |
debug(boolean) | false | 记下状态码和密钥前缀,不记密钥全文 |
libVersion(String) | 构建时写入 | 写进 context.library.version |
行为
| 项 | 值 |
|---|---|
| 队列 | 内存,默认 1000 条,满了丢最旧 |
| 批量 | 100 条或 500ms |
| 压缩 | 单批超过 32KB 用 gzip |
| 重试 | 网络失败、超时、429、5xx 按 200ms 起退避,最多 5 次,沿用同一个 messageId;400、401 不重试 |
| 线程 | 一个后台守护线程负责发送 |
| 日志 | System.Logger,名字是 cc.mosong.evstats.sdk |