16 KiB
16 KiB
天远 API 服务器重构方案
🎯 重构目标
- 提高代码可维护性 - 清晰的业务边界和模块划分
- 增强系统扩展性 - 松耦合的微服务架构
- 改善开发效率 - 标准化的开发流程和工具链
- 提升系统可靠性 - 完善的监控、测试和部署体系
🏗️ 架构重构
1. 业务域重新设计 (DDD)
新的业务域架构:
┌─────────────────────────────────────────────────────────────┐
│ API Gateway │
│ (统一入口网关) │
└─────────────────────────────────────────────────────────────┘
│
┌──────────────┼──────────────┐
│ │ │
┌───────────────▼──┐ ┌─────────▼──────┐ ┌────▼──────────┐
│ 用户域服务 │ │ 金融域服务 │ │ 数据服务域 │
│ (User Domain) │ │(Financial Domain)│ │(Data Domain) │
├─────────────────┤ ├─────────────────┤ ├──────────────┤
│• 用户认证 │ │• 钱包管理 │ │• 风险评估 │
│• 用户信息 │ │• 支付处理 │ │• 征信查询 │
│• 企业认证 │ │• 计费结算 │ │• 企业信息 │
│• 权限管理 │ │• 财务报表 │ │• 数据查询 │
└─────────────────┘ └─────────────────┘ └──────────────┘
│
┌──────────────┼──────────────┐
│ │ │
┌───────────────▼──┐ ┌─────────▼──────┐ ┌────▼──────────┐
│ 产品域服务 │ │ 平台域服务 │ │ 基础设施域 │
│(Product Domain) │ │(Platform Domain)│ │(Infra Domain) │
├─────────────────┤ ├─────────────────┤ ├──────────────┤
│• 产品目录 │ │• 管理后台 │ │• 消息队列 │
│• 产品订阅 │ │• 系统监控 │ │• 缓存服务 │
│• 访问控制 │ │• 日志管理 │ │• 配置中心 │
│• 白名单管理 │ │• 运维工具 │ │• 服务发现 │
└─────────────────┘ └─────────────────┘ └──────────────┘
2. 微服务重新设计
用户域 (User Domain)
// 用户认证服务
user-auth-service/
├── api/
│ ├── auth.proto # gRPC 接口定义
│ └── auth.api # HTTP 接口定义
├── internal/
│ ├── domain/ # 领域模型
│ ├── application/ # 应用服务
│ ├── infrastructure/ # 基础设施
│ └── interfaces/ # 接口适配器
└── cmd/
└── main.go
// 企业认证服务
enterprise-service/
├── api/
├── internal/
└── cmd/
金融域 (Financial Domain)
// 钱包服务
wallet-service/
├── api/
├── internal/
│ ├── domain/
│ │ ├── wallet/ # 钱包聚合根
│ │ ├── transaction/ # 交易实体
│ │ └── balance/ # 余额值对象
│ ├── application/
│ └── infrastructure/
└── cmd/
// 支付服务
payment-service/
├── api/
├── internal/
└── cmd/
数据服务域 (Data Service Domain)
// 统一数据服务网关
data-gateway-service/
├── api/
├── internal/
│ ├── adapters/ # 第三方数据源适配器
│ │ ├── westdex/ # 西部数据源
│ │ ├── baidu/ # 百度接口
│ │ └── aliyun/ # 阿里云接口
│ ├── domain/
│ │ ├── query/ # 查询服务
│ │ ├── risk/ # 风险评估
│ │ └── credit/ # 征信服务
│ └── application/
└── cmd/
产品域 (Product Domain)
// 产品管理服务
product-service/
├── api/
├── internal/
│ ├── domain/
│ │ ├── product/ # 产品聚合根
│ │ ├── subscription/ # 订阅实体
│ │ └── access/ # 访问控制
│ └── application/
└── cmd/
🛠️ 技术重构
1. 代码结构标准化
采用六边形架构 (Hexagonal Architecture):
service/
├── api/ # 接口定义
│ ├── grpc/ # gRPC 协议
│ ├── http/ # HTTP 协议
│ └── event/ # 事件协议
├── internal/
│ ├── domain/ # 领域层
│ │ ├── entity/ # 实体
│ │ ├── valueobject/ # 值对象
│ │ ├── aggregate/ # 聚合根
│ │ ├── repository/ # 仓储接口
│ │ └── service/ # 领域服务
│ ├── application/ # 应用层
│ │ ├── command/ # 命令处理
│ │ ├── query/ # 查询处理
│ │ ├── dto/ # 数据传输对象
│ │ └── service/ # 应用服务
│ ├── infrastructure/ # 基础设施层
│ │ ├── persistence/ # 持久化
│ │ ├── messaging/ # 消息传递
│ │ ├── external/ # 外部服务
│ │ └── config/ # 配置
│ └── interfaces/ # 接口适配器层
│ ├── grpc/ # gRPC 适配器
│ ├── http/ # HTTP 适配器
│ ├── event/ # 事件适配器
│ └── cli/ # 命令行适配器
├── pkg/ # 共享包
├── test/ # 测试
├── docs/ # 文档
├── deployments/ # 部署配置
├── Dockerfile
└── go.mod
2. 技术栈升级
推荐的技术栈:
# 微服务框架
framework: go-zero v1.6+ 或 go-kit v0.12+
# 数据库
database:
- PostgreSQL 15+ (替代MySQL, 更好的JSON支持)
- Redis 7+ (缓存和会话)
- ClickHouse (日志和分析)
# 消息队列
messaging:
- Apache Kafka 3.0+ (事件流)
- RabbitMQ 3.11+ (任务队列)
# 服务治理
service_mesh: Istio 1.17+
service_discovery: Consul 1.15+
configuration: Consul KV 或 etcd
# 监控和可观测性
monitoring:
- Prometheus + Grafana
- Jaeger (分布式追踪)
- ELK Stack (日志)
- SkyWalking (APM)
# 安全
security:
- Vault (密钥管理)
- OPA (策略引擎)
- Keycloak (身份认证)
📊 数据层重构
1. 数据库重新设计
按业务域分离数据库:
-- 用户域数据库
user_db:
- users
- user_profiles
- user_sessions
- enterprise_auth
-- 金融域数据库
financial_db:
- wallets
- transactions
- payment_orders
- billing_records
-- 产品域数据库
product_db:
- products
- product_subscriptions
- access_policies
- whitelists
-- 平台域数据库
platform_db:
- api_logs
- system_configs
- admin_users
- audit_logs
2. 数据一致性策略
事件驱动架构:
// 事件定义
type UserRegistered struct {
UserID int64 `json:"user_id"`
Username string `json:"username"`
Email string `json:"email"`
Timestamp time.Time `json:"timestamp"`
}
type WalletCreated struct {
UserID int64 `json:"user_id"`
WalletID string `json:"wallet_id"`
Balance float64 `json:"balance"`
Timestamp time.Time `json:"timestamp"`
}
// 事件处理
func (h *WalletEventHandler) HandleUserRegistered(event UserRegistered) error {
// 为新用户创建钱包
return h.walletService.CreateWallet(event.UserID)
}
🔧 开发流程重构
1. 代码生成和模板
统一的代码生成器:
# 使用 protobuf 和 API 定义生成代码
make generate-service name=user-auth
make generate-api name=wallet
# 生成的目录结构
generated/
├── user-auth-service/
│ ├── pb/ # protobuf 生成
│ ├── client/ # 客户端代码
│ ├── server/ # 服务端代码
│ └── mock/ # 测试桩
2. 测试策略
多层次测试:
// 单元测试
func TestWalletService_Transfer(t *testing.T) {
// 领域逻辑测试
}
// 集成测试
func TestWalletAPI_Transfer(t *testing.T) {
// API 集成测试
}
// 契约测试
func TestWalletService_Contract(t *testing.T) {
// 服务间契约测试
}
// 端到端测试
func TestTransferWorkflow(t *testing.T) {
// 完整业务流程测试
}
3. CI/CD 流水线
GitOps 工作流:
# .github/workflows/service.yml
name: Service CI/CD
on:
push:
paths: ["services/user-auth/**"]
pull_request:
paths: ["services/user-auth/**"]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run tests
run: make test-user-auth
build:
needs: test
runs-on: ubuntu-latest
steps:
- name: Build image
run: make build-user-auth
- name: Push to registry
run: make push-user-auth
deploy:
needs: build
runs-on: ubuntu-latest
if: github.ref == 'refs/heads/main'
steps:
- name: Deploy to staging
run: make deploy-user-auth-staging
📱 API 设计重构
1. RESTful API 标准化
统一的 API 设计规范:
// 资源命名
GET /api/v1/users # 获取用户列表
GET /api/v1/users/{id} # 获取用户详情
POST /api/v1/users # 创建用户
PUT /api/v1/users/{id} # 更新用户
DELETE /api/v1/users/{id} # 删除用户
// 子资源
GET /api/v1/users/{id}/wallets # 获取用户钱包
POST /api/v1/users/{id}/wallets # 创建用户钱包
// 统一响应格式
type APIResponse struct {
Code int `json:"code"`
Message string `json:"message"`
Data interface{} `json:"data,omitempty"`
Meta *Meta `json:"meta,omitempty"`
}
type Meta struct {
Page int `json:"page,omitempty"`
PerPage int `json:"per_page,omitempty"`
Total int `json:"total,omitempty"`
TotalPages int `json:"total_pages,omitempty"`
}
2. GraphQL 支持
为复杂查询提供 GraphQL:
type User {
id: ID!
username: String!
email: String!
wallet: Wallet
subscriptions: [ProductSubscription!]!
}
type Query {
user(id: ID!): User
users(filter: UserFilter, pagination: Pagination): UserConnection
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
}
🔒 安全重构
1. 认证授权统一化
OAuth 2.0 + RBAC:
// 角色定义
type Role struct {
ID int64 `json:"id"`
Name string `json:"name"`
Permissions []Permission `json:"permissions"`
}
type Permission struct {
ID int64 `json:"id"`
Resource string `json:"resource"` // users, wallets, products
Action string `json:"action"` // read, write, delete
Scope string `json:"scope"` // own, team, all
}
// 中间件
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := extractToken(c)
claims, err := validateToken(token)
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
user, err := getUserFromClaims(claims)
if err != nil {
c.AbortWithStatus(http.StatusForbidden)
return
}
c.Set("user", user)
c.Next()
}
}
2. 数据安全
端到端加密 + 数据脱敏:
// 字段级加密
type User struct {
ID int64 `json:"id"`
Username string `json:"username"`
Email string `json:"email" encrypt:"true"`
Phone string `json:"phone" encrypt:"true" mask:"***-****-####"`
}
// 自动加密解密
func (u *User) BeforeSave() error {
return encrypt.EncryptStruct(u)
}
func (u *User) AfterFind() error {
return encrypt.DecryptStruct(u)
}
📈 监控和可观测性
1. 分布式追踪
OpenTelemetry 集成:
func (s *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.User, error) {
span := trace.SpanFromContext(ctx)
span.SetAttributes(
attribute.String("user.username", req.Username),
attribute.String("operation", "create_user"),
)
// 业务逻辑
user, err := s.userRepo.Create(ctx, req)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return nil, err
}
// 发送事件
event := UserCreatedEvent{UserID: user.ID, Username: user.Username}
if err := s.eventBus.Publish(ctx, event); err != nil {
s.logger.Error("failed to publish event", zap.Error(err))
}
return user, nil
}
2. 业务指标监控
自定义业务指标:
var (
userRegistrations = prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "user_registrations_total",
Help: "Total number of user registrations",
},
[]string{"source", "status"},
)
walletBalance = prometheus.NewGaugeVec(
prometheus.GaugeOpts{
Name: "wallet_balance",
Help: "Current wallet balance",
},
[]string{"user_id", "currency"},
)
)
🚀 迁移策略
阶段 1: 基础设施准备 (1-2 周)
- 搭建新的开发环境
- 建立 CI/CD 流水线
- 配置监控和日志系统
阶段 2: 用户域重构 (2-3 周)
- 重构用户认证服务
- 迁移用户数据
- 更新客户端集成
阶段 3: 金融域重构 (2-3 周)
- 重构钱包服务
- 重构支付服务
- 数据一致性验证
阶段 4: 数据服务域重构 (3-4 周)
- 重构数据网关
- 重新组织业务 API
- 性能优化
阶段 5: 产品域重构 (1-2 周)
- 重构产品管理
- 重构访问控制
- 清理遗留代码
阶段 6: 平台域完善 (1-2 周)
- 完善管理后台
- 优化监控系统
- 性能调优
📋 重构检查清单
代码质量
- 代码覆盖率 > 80%
- 静态代码分析通过
- API 文档完整
- 性能基准测试
架构质量
- 服务间松耦合
- 明确的业务边界
- 数据一致性保证
- 容错和恢复机制
运维质量
- 自动化部署
- 监控告警完整
- 日志可追溯
- 备份恢复测试
安全质量
- 认证授权机制
- 数据加密传输
- 漏洞扫描通过
- 安全策略文档
🎯 预期收益
- 开发效率提升 40% - 通过标准化和自动化
- 系统可靠性提升 60% - 通过完善的测试和监控
- 维护成本降低 50% - 通过清晰的架构和文档
- 新功能交付速度提升 3 倍 - 通过模块化设计
重构是一个渐进的过程,建议分阶段实施,确保每个阶段都有明确的交付物和验收标准。