# Revoke Trace 示例
这个目录包含了使用 revoke-trace 与 Axum 集成的各种示例。
## 示例列表
1. **basic.rs** - 基本的追踪使用示例
2. **axum_integration.rs** - 完整的 Axum 应用集成示例
3. **axum_middleware.rs** - 可重用的追踪中间件
4. **distributed_tracing.rs** - 分布式追踪示例(多服务)
## 运行示例
### 1. 启动追踪基础设施
首先,使用 Docker Compose 启动 Jaeger 和 OpenTelemetry Collector:
```bash
cd examples
docker-compose up -d
```
这将启动:
- Jaeger UI: http://localhost:16686
- OpenTelemetry Collector: localhost:4317 (gRPC), localhost:4318 (HTTP)
- Prometheus: http://localhost:9090
- Grafana: http://localhost:3000 (admin/admin)
### Prometheus 3.0 原生 OTLP 支持
从 Prometheus 3.0 开始,原生支持接收 OTLP 数据:
```bash
# 使用 Prometheus 3.0 的 Docker Compose
docker-compose -f docker-compose.yml up -d
# 配置应用直接发送指标到 Prometheus 3.0
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=http://localhost:9090/api/v1/otlp/v1/metrics
```
### 2. 运行基本示例
```bash
cargo run --example basic
```
### 3. 运行 Axum 集成示例
```bash
cargo run --example axum_integration --features otlp
```
然后访问以下端点:
- http://localhost:3000/ - 根路径
- http://localhost:3000/api/users - 用户列表
- http://localhost:3000/api/users/1 - 获取特定用户
- http://localhost:3000/api/orders - 订单列表
- http://localhost:3000/health - 健康检查
### 4. 运行分布式追踪示例
这个示例展示了多个微服务之间的追踪传播:
```bash
cargo run --example distributed_tracing --features otlp
```
这将启动三个服务:
- API Gateway (端口 8080)
- Product Service (端口 8081)
- Inventory Service (端口 8082)
测试调用链:
```bash
# 获取产品(会调用产品服务和库存服务)
curl http://localhost:8080/api/products/1
# 创建订单(会验证多个产品的库存)
curl -X POST http://localhost:8080/api/orders \
-H "Content-Type: application/json" \
-d '{
"user_id": 123,
"items": [
{"product_id": 1, "quantity": 2},
{"product_id": 2, "quantity": 1}
]
}'
```
## 查看追踪数据
1. 打开 Jaeger UI: http://localhost:16686
2. 在服务列表中选择你的服务(如 "axum-example")
3. 点击 "Find Traces" 查看追踪数据
4. 点击具体的追踪查看详细的调用链
## 追踪中间件使用
`axum_middleware.rs` 提供了一个可重用的追踪中间件。在你的应用中使用:
```rust
use revoke_trace_examples::tracing_layer;
let app = Router::new()
.route("/", get(handler))
.layer(tracing_layer(TracingConfig {
service_name: "my-service".to_string(),
ignored_paths: vec!["/health".to_string()],
..Default::default()
}));
```
## 最佳实践
1. **使用结构化日志**:配合 `tracing` crate 的结构化日志功能
2. **设置合适的 Span 类型**:Server、Client、Producer、Consumer
3. **添加有意义的属性**:遵循 OpenTelemetry 语义约定
4. **处理错误状态**:正确设置 Span 状态和错误信息
5. **传播上下文**:在服务间调用时传播追踪上下文
## 故障排除
### 没有看到追踪数据
1. 确保 Docker 容器正在运行:`docker-compose ps`
2. 检查应用日志是否有错误
3. 确认 OTLP 端点配置正确(默认 http://localhost:4317)
4. 在 Jaeger UI 中刷新并选择正确的服务名称
### 追踪数据不完整
1. 确保在服务间调用时正确传播了追踪上下文
2. 检查采样配置(默认是 AlwaysOn)
3. 等待几秒钟让数据完全导出
## 清理
停止并清理所有容器:
```bash
docker-compose down -v
```