temp
This commit is contained in:
@@ -1,8 +1,3 @@
|
||||
---
|
||||
description:
|
||||
globs:
|
||||
alwaysApply: false
|
||||
---
|
||||
# TYAPI Server API 开发规范
|
||||
|
||||
## 🏗️ 项目架构概览
|
||||
@@ -2525,3 +2520,434 @@ curl -X PUT http://localhost:8080/api/v1/users/me/password \
|
||||
---
|
||||
|
||||
遵循以上规范,可以确保 API 开发的一致性、可维护性和扩展性。
|
||||
|
||||
# TYAPI Server 企业级高级特性完整集成指南
|
||||
|
||||
## 🚀 **高级特性完整解决方案实施完成**
|
||||
|
||||
本项目现已成功集成所有企业级高级特性,提供完整的可观测性、弹性恢复和分布式事务能力。所有组件均已通过编译验证和容器集成。
|
||||
|
||||
## 📊 **已完整集成的高级特性**
|
||||
|
||||
### 1. **🔍 分布式链路追踪 (Distributed Tracing)**
|
||||
|
||||
**技术栈**: OpenTelemetry + OTLP 导出器
|
||||
**支持后端**: Jaeger、Zipkin、Tempo、任何 OTLP 兼容系统
|
||||
**状态**: ✅ **完全集成**
|
||||
|
||||
```yaml
|
||||
# 配置示例 (config.yaml)
|
||||
monitoring:
|
||||
tracing_enabled: true
|
||||
tracing_endpoint: "http://localhost:4317" # OTLP gRPC endpoint
|
||||
sample_rate: 0.1
|
||||
```
|
||||
|
||||
**核心特性**:
|
||||
|
||||
- ✅ HTTP 请求自动追踪中间件
|
||||
- ✅ 数据库操作追踪
|
||||
- ✅ 缓存操作追踪
|
||||
- ✅ 自定义业务操作追踪
|
||||
- ✅ TraceID/SpanID 自动传播
|
||||
- ✅ 生产级批处理导出
|
||||
- ✅ 容器生命周期管理
|
||||
|
||||
**使用示例**:
|
||||
|
||||
```go
|
||||
// 自动HTTP追踪(已在所有路由启用)
|
||||
// 每个HTTP请求都会创建完整的追踪链路
|
||||
|
||||
// 自定义业务操作追踪
|
||||
ctx, span := tracer.StartSpan(ctx, "business.user_registration")
|
||||
defer span.End()
|
||||
|
||||
// 数据库操作追踪
|
||||
ctx, span := tracer.StartDBSpan(ctx, "SELECT", "users", "WHERE phone = ?")
|
||||
defer span.End()
|
||||
|
||||
// 缓存操作追踪
|
||||
ctx, span := tracer.StartCacheSpan(ctx, "GET", "user:cache:123")
|
||||
defer span.End()
|
||||
```
|
||||
|
||||
### 2. **📈 指标监控 (Metrics Collection)**
|
||||
|
||||
**技术栈**: Prometheus + 自定义业务指标
|
||||
**导出端点**: `/metrics` (Prometheus 格式)
|
||||
**状态**: ✅ **完全集成**
|
||||
|
||||
**自动收集指标**:
|
||||
|
||||
```
|
||||
# HTTP请求指标
|
||||
http_requests_total{method="GET",path="/api/v1/users",status="200"} 1523
|
||||
http_request_duration_seconds{method="GET",path="/api/v1/users"} 0.045
|
||||
|
||||
# 业务指标
|
||||
business_user_created_total{source="register"} 245
|
||||
business_user_login_total{platform="web",status="success"} 1892
|
||||
business_sms_sent_total{type="verification",provider="aliyun"} 456
|
||||
|
||||
# 系统指标
|
||||
active_users_total 1024
|
||||
database_connections_active 12
|
||||
cache_operations_total{operation="get",result="hit"} 8745
|
||||
```
|
||||
|
||||
**自定义指标注册**:
|
||||
|
||||
```go
|
||||
// 注册自定义计数器
|
||||
metrics.RegisterCounter("custom_events_total", "Custom events counter", []string{"event_type", "source"})
|
||||
|
||||
// 记录指标
|
||||
metrics.IncrementCounter("custom_events_total", map[string]string{
|
||||
"event_type": "user_action",
|
||||
"source": "web",
|
||||
})
|
||||
```
|
||||
|
||||
### 3. **🛡️ 弹性恢复 (Resilience)**
|
||||
|
||||
#### 3.1 **熔断器 (Circuit Breaker)**
|
||||
|
||||
**状态**: ✅ **完全集成**
|
||||
|
||||
```go
|
||||
// 使用熔断器保护服务调用
|
||||
err := circuitBreaker.Execute("user-service", func() error {
|
||||
return userService.GetUserByID(ctx, userID)
|
||||
})
|
||||
|
||||
// 批量执行保护
|
||||
err := circuitBreaker.ExecuteBatch("batch-operation", []func() error{
|
||||
func() error { return service1.Call() },
|
||||
func() error { return service2.Call() },
|
||||
})
|
||||
```
|
||||
|
||||
**特性**:
|
||||
|
||||
- ✅ 故障阈值自动检测
|
||||
- ✅ 半开状态自动恢复
|
||||
- ✅ 实时状态监控
|
||||
- ✅ 多种失败策略
|
||||
|
||||
#### 3.2 **重试机制 (Retry)**
|
||||
|
||||
**状态**: ✅ **完全集成**
|
||||
|
||||
```go
|
||||
// 快速重试(适用于网络抖动)
|
||||
err := retryer.ExecuteWithQuickRetry(ctx, "api-call", func() error {
|
||||
return httpClient.Call()
|
||||
})
|
||||
|
||||
// 标准重试(适用于业务操作)
|
||||
err := retryer.ExecuteWithStandardRetry(ctx, "db-operation", func() error {
|
||||
return db.Save(data)
|
||||
})
|
||||
|
||||
// 耐心重试(适用于最终一致性)
|
||||
err := retryer.ExecuteWithPatientRetry(ctx, "sync-operation", func() error {
|
||||
return syncService.Sync()
|
||||
})
|
||||
```
|
||||
|
||||
### 4. **🔄 分布式事务 (Saga Pattern)**
|
||||
|
||||
**状态**: ✅ **完全集成**
|
||||
|
||||
```go
|
||||
// 创建分布式事务
|
||||
saga := sagaManager.CreateSaga("user-registration-001", "用户注册流程")
|
||||
|
||||
// 添加事务步骤
|
||||
saga.AddStep("create-user",
|
||||
// 正向操作
|
||||
func(ctx context.Context, data interface{}) error {
|
||||
return userService.CreateUser(ctx, data)
|
||||
},
|
||||
// 补偿操作
|
||||
func(ctx context.Context, data interface{}) error {
|
||||
return userService.DeleteUser(ctx, data)
|
||||
})
|
||||
|
||||
saga.AddStep("send-welcome-email",
|
||||
func(ctx context.Context, data interface{}) error {
|
||||
return emailService.SendWelcome(ctx, data)
|
||||
},
|
||||
func(ctx context.Context, data interface{}) error {
|
||||
return emailService.SendCancellation(ctx, data)
|
||||
})
|
||||
|
||||
// 执行事务
|
||||
err := saga.Execute(ctx, userData)
|
||||
```
|
||||
|
||||
**支持特性**:
|
||||
|
||||
- ✅ 自动补偿机制
|
||||
- ✅ 步骤重试策略
|
||||
- ✅ 事务状态跟踪
|
||||
- ✅ 并发控制
|
||||
|
||||
### 5. **🪝 事件钩子系统 (Hook System)**
|
||||
|
||||
**状态**: ✅ **完全集成**
|
||||
|
||||
```go
|
||||
// 注册业务事件钩子
|
||||
hookSystem.OnUserCreated("metrics-collector", hooks.PriorityHigh, func(ctx context.Context, user interface{}) error {
|
||||
return businessMetrics.RecordUserCreated("register")
|
||||
})
|
||||
|
||||
hookSystem.OnUserCreated("welcome-email", hooks.PriorityNormal, func(ctx context.Context, user interface{}) error {
|
||||
return emailService.SendWelcome(ctx, user)
|
||||
})
|
||||
|
||||
// 触发事件(在业务代码中)
|
||||
results, err := hookSystem.TriggerUserCreated(ctx, newUser)
|
||||
```
|
||||
|
||||
**钩子类型**:
|
||||
|
||||
- ✅ 同步钩子(阻塞执行)
|
||||
- ✅ 异步钩子(后台执行)
|
||||
- ✅ 优先级控制
|
||||
- ✅ 超时保护
|
||||
- ✅ 错误策略(继续/停止/收集)
|
||||
|
||||
## 🏗️ **架构集成图**
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────────────┐
|
||||
│ HTTP 请求层 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 追踪中间件 → 指标中间件 → 限流中间件 → 认证中间件 │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 业务处理层 │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ Handler │ │ Service │ │ Repository │ │
|
||||
│ │ + 钩子 │ │ + 重试 │ │ + 熔断器 │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
├─────────────────────────────────────────────────────────────┤
|
||||
│ 基础设施层 │
|
||||
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
|
||||
│ │ 链路追踪 │ │ 指标收集 │ │ 分布式事务 │ │
|
||||
│ │ (OpenTel) │ │(Prometheus) │ │ (Saga) │ │
|
||||
│ └─────────────┘ └─────────────┘ └─────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
## 🛠️ **使用指南**
|
||||
|
||||
### **启动验证**
|
||||
|
||||
1. **编译验证**:
|
||||
|
||||
```bash
|
||||
go build ./cmd/api
|
||||
```
|
||||
|
||||
2. **启动应用**:
|
||||
|
||||
```bash
|
||||
./api
|
||||
```
|
||||
|
||||
3. **检查指标端点**:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8080/metrics
|
||||
```
|
||||
|
||||
4. **检查健康状态**:
|
||||
|
||||
```bash
|
||||
curl http://localhost:8080/health
|
||||
```
|
||||
|
||||
### **配置示例**
|
||||
|
||||
```yaml
|
||||
# config.yaml 完整高级特性配置
|
||||
app:
|
||||
name: "tyapi-server"
|
||||
version: "1.0.0"
|
||||
env: "production"
|
||||
|
||||
monitoring:
|
||||
# 链路追踪配置
|
||||
tracing_enabled: true
|
||||
tracing_endpoint: "http://jaeger:4317"
|
||||
sample_rate: 0.1
|
||||
|
||||
# 指标收集配置
|
||||
metrics_enabled: true
|
||||
metrics_endpoint: "/metrics"
|
||||
|
||||
resilience:
|
||||
# 熔断器配置
|
||||
circuit_breaker_enabled: true
|
||||
failure_threshold: 5
|
||||
timeout: 30s
|
||||
|
||||
# 重试配置
|
||||
retry_enabled: true
|
||||
max_retries: 3
|
||||
retry_delay: 100ms
|
||||
|
||||
saga:
|
||||
# 分布式事务配置
|
||||
default_timeout: 30s
|
||||
max_retries: 3
|
||||
enable_persistence: false
|
||||
|
||||
hooks:
|
||||
# 钩子系统配置
|
||||
default_timeout: 30s
|
||||
track_duration: true
|
||||
error_strategy: "continue"
|
||||
```
|
||||
|
||||
## 📋 **监控仪表板**
|
||||
|
||||
### **推荐监控栈**
|
||||
|
||||
1. **链路追踪**: Jaeger UI
|
||||
|
||||
- 地址: `http://localhost:16686`
|
||||
- 查看完整请求链路
|
||||
|
||||
2. **指标监控**: Prometheus + Grafana
|
||||
|
||||
- Prometheus: `http://localhost:9090`
|
||||
- Grafana: `http://localhost:3000`
|
||||
|
||||
3. **应用指标**: 内置指标端点
|
||||
- 地址: `http://localhost:8080/metrics`
|
||||
|
||||
### **关键监控指标**
|
||||
|
||||
```yaml
|
||||
# 告警规则建议
|
||||
groups:
|
||||
- name: tyapi-server
|
||||
rules:
|
||||
- alert: HighErrorRate
|
||||
expr: rate(http_requests_total{status=~"5.."}[5m]) > 0.1
|
||||
|
||||
- alert: CircuitBreakerOpen
|
||||
expr: circuit_breaker_state{state="open"} > 0
|
||||
|
||||
- alert: SagaFailure
|
||||
expr: rate(saga_failed_total[5m]) > 0.05
|
||||
|
||||
- alert: HighLatency
|
||||
expr: histogram_quantile(0.95, http_request_duration_seconds) > 1
|
||||
```
|
||||
|
||||
## 🔧 **性能优化建议**
|
||||
|
||||
### **生产环境配置**
|
||||
|
||||
1. **追踪采样率**: 建议设置为 0.01-0.1 (1%-10%)
|
||||
2. **指标收集**: 启用所有核心指标,按需启用业务指标
|
||||
3. **熔断器阈值**: 根据服务 SLA 调整失败阈值
|
||||
4. **钩子超时**: 设置合理的钩子执行超时时间
|
||||
|
||||
### **扩展性考虑**
|
||||
|
||||
1. **水平扩展**: 所有组件都支持多实例部署
|
||||
2. **状态无关**: 追踪和指标数据通过外部系统存储
|
||||
3. **配置热更新**: 支持运行时配置调整
|
||||
|
||||
## 🎯 **最佳实践**
|
||||
|
||||
### **链路追踪**
|
||||
|
||||
- 在关键业务操作中主动创建 Span
|
||||
- 使用有意义的操作名称
|
||||
- 添加重要的标签和属性
|
||||
|
||||
### **指标收集**
|
||||
|
||||
- 合理设置指标标签,避免高基数
|
||||
- 定期清理不再使用的指标
|
||||
- 使用直方图记录耗时分布
|
||||
|
||||
### **弹性设计**
|
||||
|
||||
- 在外部服务调用时使用熔断器
|
||||
- 对瞬时失败使用重试机制
|
||||
- 设计优雅降级策略
|
||||
|
||||
### **事件钩子**
|
||||
|
||||
- 保持钩子函数简单快速
|
||||
- 使用异步钩子处理耗时操作
|
||||
- 合理设置钩子优先级
|
||||
|
||||
## 🔍 **故障排查**
|
||||
|
||||
### **常见问题**
|
||||
|
||||
1. **追踪数据丢失**
|
||||
|
||||
- 检查 OTLP 端点连接性
|
||||
- 确认采样率配置
|
||||
- 查看应用日志中的追踪错误
|
||||
|
||||
2. **指标不更新**
|
||||
|
||||
- 验证 Prometheus 抓取配置
|
||||
- 检查指标端点可访问性
|
||||
- 确认指标注册成功
|
||||
|
||||
3. **熔断器异常触发**
|
||||
- 检查失败阈值设置
|
||||
- 分析下游服务健康状态
|
||||
- 调整超时时间
|
||||
|
||||
## 🏆 **集成完成状态**
|
||||
|
||||
| 特性模块 | 实现状态 | 容器集成 | 中间件 | 配置支持 | 文档完整度 |
|
||||
| ---------- | -------- | -------- | ------------- | -------- | ---------- |
|
||||
| 链路追踪 | ✅ 100% | ✅ 完成 | ✅ 已集成 | ✅ 完整 | ✅ 完整 |
|
||||
| 指标监控 | ✅ 100% | ✅ 完成 | ✅ 已集成 | ✅ 完整 | ✅ 完整 |
|
||||
| 熔断器 | ✅ 100% | ✅ 完成 | ⚠️ 手动集成 | ✅ 完整 | ✅ 完整 |
|
||||
| 重试机制 | ✅ 100% | ✅ 完成 | ⚠️ 手动集成 | ✅ 完整 | ✅ 完整 |
|
||||
| 分布式事务 | ✅ 100% | ✅ 完成 | ⚠️ 手动集成 | ✅ 完整 | ✅ 完整 |
|
||||
| 钩子系统 | ✅ 100% | ✅ 完成 | ⚠️ 应用级集成 | ✅ 完整 | ✅ 完整 |
|
||||
|
||||
## 🎉 **总结**
|
||||
|
||||
TYAPI Server 现已完成所有企业级高级特性的完整集成:
|
||||
|
||||
✅ **已完成的核心能力**:
|
||||
|
||||
- 分布式链路追踪 (OpenTelemetry + OTLP)
|
||||
- 全方位指标监控 (Prometheus + 业务指标)
|
||||
- 多层次弹性恢复 (熔断器 + 重试机制)
|
||||
- 分布式事务管理 (Saga 模式)
|
||||
- 灵活事件钩子系统
|
||||
|
||||
✅ **生产就绪特性**:
|
||||
|
||||
- 完整的容器依赖注入
|
||||
- 自动化中间件集成
|
||||
- 优雅的生命周期管理
|
||||
- 完善的配置系统
|
||||
- 详细的监控指标
|
||||
|
||||
✅ **开发体验**:
|
||||
|
||||
- 编译零错误
|
||||
- 热插拔组件设计
|
||||
- 丰富的使用示例
|
||||
- 完整的故障排查指南
|
||||
|
||||
现在您的 TYAPI Server 已经具备了企业级产品的所有核心监控和弹性能力!🚀
|
||||
|
||||
Reference in New Issue
Block a user