Files
go-sms-V2/memory-bank/docs/Go-sms-技术方案.md
T

48 KiB
Raw Blame History

Go-sms 技术方案

【文档状态】✅ 重建架构基线(判定 2026-11-12) §1-10 设计经 POC 实测修订后有效;§11 项目结构以 POC 实际演化结构为准(35 包 -race 全绿验证),差异裁决与强制结论见《Go-sms-重建设计规范.md》。

1. 总体架构设计

1.1 架构原则

原则 说明
高可用 多机房/多可用区部署,故障自动切换,降级熔断,数据多副本
低延时 本地缓存+Redis,连接池复用,异步非阻塞I/O,P99 < 50ms
高并发 水平扩展,消息队列削峰,协程池管控,单机支撑10万QPS

1.2 整体架构图

┌─────────────────────────────────────────────────────────────────────────────┐
│                             接入层 (Ingress)                                 │
│                    Nginx + LVS + Keepalived (四层/七层)                      │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
┌─────────────────────────────────────────────────────────────────────────────┐
│                             网关层 (Gateway)                                 │
│              Go Gateway (HTTP/CMPP/SMPP协议适配,限流/鉴权)                    │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
┌─────────────────────────────────────────────────────────────────────────────┐
│                            业务层 (Business)                                 │
│  ┌──────────┬──────────┬──────────┬──────────┬──────────┬──────────┐        │
│  │ 用户服务  │ 通道服务  │ 发送服务  │ 审核服务  │ 路由服务  │ 计费服务    │        │
│  ├──────────┼──────────┼──────────┼──────────┼──────────┼──────────┤        │
│  │ 统计服务  │ 结算服务  │ 告警服务  │ 短链服务  │ 空号服务  │ CSP服务  │           │
│  └──────────┴──────────┴──────────┴──────────┴──────────┴──────────┘        │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
┌─────────────────────────────────────────────────────────────────────────────┐
│                          中间件层 (Middleware)                             │
│  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌────────┐ │
│  │ Redis   │ │  Kafka  │ │  ETCD   │ │  ES     │ │ ClickHouse│ │  Prometheus│
│  │(缓存/锁)│ │(消息队列)│ │(配置/服务发现)│ │(日志检索)│ │(历史统计)│ │(监控)   │
│  └─────────┘ └─────────┘ └─────────┘ └─────────┘ └─────────┘ └────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
┌─────────────────────────────────────────────────────────────────────────────┐
│                            数据层 (Storage)                                │
│  ┌─────────────────────┐ ┌─────────────────────┐ ┌─────────────────────┐ │
│  │  MySQL Cluster      │ │  TiDB (历史数据)      │ │  OSS/S3 (文件存储)  │ │
│  │  (业务主库+读写分离)   │ │  (全量历史明细)       │ │  (号码文件/报表)    │ │
│  └─────────────────────┘ └─────────────────────┘ └─────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
┌─────────────────────────────────────────────────────────────────────────────┐
│                           上游通道层 (Upstream)                               │
│            CMPP/HTTP/SGIP/SMPP 运营商直连 & 第三方通道                          │
└─────────────────────────────────────────────────────────────────────────────┘

2. 技术栈选型

2.1 核心框架与库

层级 技术选型 版本 选型理由
Web框架 Gin v1.10+ 高性能HTTP路由,中间件生态丰富
微服务框架 Go-kratos 或 Go-zero v2.7+ 服务治理、可观测性、代码生成
ORM GORM + 自定义DAO v1.25+ 开发效率高,支持连接池和钩子
缓存客户端 go-redis/v9 v9.5+ 高性能Redis客户端,支持集群/哨兵
消息队列 Sarama (Kafka) v1.43+ 高吞吐,支持Exactly-Once语义
服务发现/配置 ETCD (clientv3) v3.5+ 强一致性,支持Watch和Lease
RPC框架 gRPC v1.64+ 高性能二进制协议,多语言支持
日志 Zap + Lumberjack v1.27+ 高性能结构化日志,自动切割
监控指标 Prometheus client v1.19+ 标准指标采集,与Grafana集成
链路追踪 Jaeger (OpenTelemetry) v1.24+ 分布式追踪,定位慢请求
并发控制 ants (协程池) v2.10+ 控制协程数量,防止资源耗尽
配置管理 Viper v1.18+ 多配置源支持,热加载
参数校验 go-playground/validator v10.20+ 结构体标签校验,灵活扩展
限流器 uber-go/ratelimit + 令牌桶 - 毫秒级限流,支持动态调整
熔断器 gobreaker / hystrix-go - 故障隔离,快速失败

2.2 存储与中间件

组件 用途 部署模式
MySQL 8.0 用户、通道、配置、余额、结算等事务性数据 主从+读写分离,MGR高可用
Redis Cluster 缓存、分布式锁、实时计数、会话、限流令牌 集群模式,6节点+哨兵
Kafka 发送任务、回执、上行、统计事件、日志 3节点集群,分区副本≥2
ClickHouse 下行明细、上行记录、统计报表(历史+实时) 分布式集群,多分片
Elasticsearch 操作日志、审计日志、查询检索 3节点集群
ETCD 服务注册发现、配置下发、分布式协调 3节点集群
MinIO/OSS 号码文件、报表文件、检测结果存储 分布式对象存储
Prometheus+Grafana 指标采集与可视化 单机/集群
SkyWalking/Jaeger APM与链路追踪 独立部署

3. 模块详细设计

3.1 接入网关层 (Gateway)

3.1.1 多协议适配

// 协议适配器接口
type ProtocolAdapter interface {
    ListenAndServe() error
    HandleRequest(ctx context.Context, req interface{}) (resp interface{}, err error)
    Shutdown(ctx context.Context) error
}

// 实现:HTTPAdapter, CMPPAdapter, SMPPAdapter, SGIPAdapter
协议 实现方式 关键点
HTTP Gin路由,统一API前缀 /api/v1/* 限流(令牌桶)、鉴权(JWT)、参数校验
CMPP 自定义TCP Server (v2.0/v3.0) 连接池管理、心跳保活、窗口流控
SMPP 标准SMPP 3.4协议 长连接、收发分离、ESME绑定
SGIP 标准SGIP 1.2协议 短连接池、消息序列化

3.1.2 连接与并发控制

gateway:
  http:
    max_connections: 10000
    read_timeout: 30s
    write_timeout: 30s
  cmpp:
    max_connections_per_account: 50
    idle_timeout: 60s
    window_size: 32
  smpp:
    max_connections: 1000
    enquire_link_interval: 30s

3.1.3 限流设计

// 多维度限流
type RateLimiter interface {
    Allow(key string) bool  // 全局限流
    AllowUser(userID string) bool  // 用户级限流
    AllowChannel(channelID string) bool  // 通道级限流
    AllowIP(ip string) bool  // IP级限流
}

// 实现:Redis + 令牌桶 (Lua脚本原子操作)
// 前缀:rate_limit:{key}:timestamp, 窗口滑动

3.2 路由与策略引擎

3.2.1 四步路由实现

// 路由链模式
type RoutingChain struct {
    Filters  []Filter
    Priority *PriorityRouter
    Weighted *WeightedRouter
    Fallback *FallbackRouter
}

type Filter interface {
    Apply(ctx *RouteContext) bool  // true=过滤,跳过
}

// 四步路由
// Step1: 条件过滤 (黑名单/黑关键字/签名/地区/运营商/频次)
// Step2: 优先通道 (省网分流/关键字匹配)
// Step3: 权重比例分发 (加权轮询)
// Step4: 默认通道兜底

3.2.2 规则存储与热加载

规则存储结构 (MySQL):
┌──────────────────────────────────────────────┐
│  route_rules (id, account_id, channel_id,    │
│  rule_type, rule_config, priority, status)   │
└──────────────────────────────────────────────┘
                    ↓ (Watch)
┌──────────────────────────────────────────────┐
│  ETCD: /config/routes/ {account_id}          │
│  规则变更 → 监听 → 本地缓存更新 (10s内生效)       │
└──────────────────────────────────────────────┘

3.3 消息发送核心

3.3.1 异步发送流水线

┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐
│ API接收  │ -> │ 提交预扣 │ -> │ 审核过滤 │ -> │ 路由匹配  │
└─────────┘    └─────────┘    └─────────┘    └─────────┘
                                                    │
┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐
│ 状态回执  │ <- │ 通道发送 │ <- │ 消息队列 │ <- │ 消息组装 │
└─────────┘    └─────────┘    └─────────┘    └─────────┘
      │              │              │              │
      ▼              ▼              ▼              ▼
 计费确认      通道限速       削峰填谷       模板填充

3.3.2 消息结构与状态机

// 消息实体
type Message struct {
    ID          string    `json:"id"`           // 全局唯一ID (雪花算法)
    AccountID   string    `json:"account_id"`
    Business    string    `json:"business"`     // sms/video/csp/empty
    Phone       string    `json:"phone"`
    Content     string    `json:"content"`
    TemplateID  string    `json:"template_id"`
    ChannelID   string    `json:"channel_id"`
    Status      MsgStatus `json:"status"`
    SendTime    time.Time `json:"send_time"`
    SubmitTime  time.Time `json:"submit_time"`
    Fee         int64     `json:"fee"`          // 计费条数
    Price       int64     `json:"price"`        // 单价(毫)
    ErrorCode   string    `json:"error_code"`
    RetryCount  int       `json:"retry_count"`
    Ext         map[string]interface{} `json:"ext"`
}

// 状态枚举
const (
    Pending    MsgStatus = 0 // 待提交
    Submitted  MsgStatus = 1 // 已提交通道
    Succeed    MsgStatus = 2 // 成功
    Failed     MsgStatus = 3 // 失败
    Unknown    MsgStatus = 4 // 未知(超时)
)

3.3.3 发送流程伪代码

func (s *SendService) Submit(ctx context.Context, req *SubmitRequest) error {
    // 1. 参数校验 (手机号格式、内容长度、模板变量)
    if err := s.validate(req); err != nil { return err }
    
    // 2. 预扣费 (Redis Lua原子操作)
    if err := s.balanceService.PreDeduct(ctx, req.AccountID, req.EstimatedFee); err != nil {
        return err
    }
    
    // 3. 审核 (免审/自动/手动)
    auditResult, err := s.auditService.Check(ctx, req)
    if err != nil || !auditResult.Pass {
        // 退回预扣费
        s.balanceService.Rollback(ctx, req.AccountID, req.EstimatedFee)
        return auditResult.Error
    }
    
    // 4. 频次/黑名单/地区检测 (拦截器链)
    if blocked := s.interceptorChain.Process(ctx, req); blocked {
        s.balanceService.Rollback(ctx, req.AccountID, req.EstimatedFee)
        return ErrBlocked
    }
    
    // 5. 路由选择
    routeResult, err := s.routeService.Select(ctx, req)
    if err != nil {
        s.balanceService.Rollback(ctx, req.AccountID, req.EstimatedFee)
        return err
    }
    
    // 6. 生成消息并写入Kafka (发送队列)
    msg := s.buildMessage(req, routeResult)
    if err := s.producer.Send(ctx, msg); err != nil {
        s.balanceService.Rollback(ctx, req.AccountID, req.EstimatedFee)
        return err
    }
    
    // 7. 写入热数据 (Redis预写)
    s.cache.Set(ctx, msg.ID, msg, 5*24*time.Hour)
    
    // 8. 写入ClickHouse异步
    s.asyncWrite.ClickHouse(ctx, msg)
    
    return nil
}

3.4 计费与结算

3.4.1 预扣费+实扣费设计

┌─────────────────────────────────────────────────────────────────┐
│  Redis Lua脚本 (原子操作)                                         │
│  1. 读取账号余额 balance:account:{id}                             │
│  2. 检查余额 + 授信余额 >= 预估费用                                 │
│  3. 冻结预扣金额 (临时冻结)                                        │
│  4. 返回预扣成功/失败                                              │
└─────────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────────┐
│  回执到达 → 实扣 (异步)                                            │
│  成功: 冻结金额 → 实扣记录 (SUCCESS)                                │
│  失败: 冻结金额 → 回退余额 (FAILURE)                                │
│  未知: 72h后超时释放 (UNKNOWN)                                     │
└─────────────────────────────────────────────────────────────────┘

3.4.2 分时计价实现

// 价格时间线存储
type PriceTimeline struct {
    AccountID string
    Business  string
    Prices    []PricePoint
}

type PricePoint struct {
    Price     int64     `json:"price"`
    StartTime time.Time `json:"start_time"`
    EndTime   time.Time `json:"end_time"`
}

// 查询当前生效价格
func (s *PriceService) GetCurrentPrice(ctx context.Context, accountID, business string) int64 {
    key := fmt.Sprintf("price:%s:%s", accountID, business)
    // 1. 本地缓存 (1分钟TTL)
    if val, ok := s.localCache.Get(key); ok { return val.(int64) }
    // 2. Redis缓存 (5分钟TTL)
    // 3. MySQL查询
}

3.5 审核工作流

// 审核状态机
type AuditStatus int
const (
    AuditPending  AuditStatus = 0 // 待审核
    AuditPass     AuditStatus = 1 // 通过
    AuditReject   AuditStatus = 2 // 拒绝
    AuditAutoPass AuditStatus = 3 // 免审自动通过
    AuditTimeout  AuditStatus = 4 // 超时失败
)

// 审核策略
type AuditStrategy interface {
    ShouldAudit(ctx context.Context, req *SubmitRequest) (bool, error)
}

// 实现: NoAuditStrategy (免审), ManualAuditStrategy (人工审), AutoAuditStrategy (自动审)

定时清理任务:

// 48小时超时审核自动失败
func (s *AuditService) TimeoutCleaner(ctx context.Context) {
    ticker := time.NewTicker(1 * time.Hour)
    for {
        select {
        case <-ticker.C:
            // 查询待审核>48h的记录,标记为失败,回退预扣费
            s.processTimeoutAudits(ctx)
        }
    }
}

3.6 通道管理

3.6.1 通道连接池

// 通道连接池 (CMPP)
type ChannelPool struct {
    mu       sync.RWMutex
    conns    map[string]*ChannelConnection
    maxSize  int
    factory  ConnectionFactory
}

type ChannelConnection struct {
    Conn     net.Conn
    Reader   *bufio.Reader
    Writer   *bufio.Writer
    SeqID    uint32
    Mutex    sync.Mutex
    LastUsed time.Time
    Status   ConnStatus
}

3.6.2 限速实现

// 通道级别限速器 (滑动窗口计数)
type ChannelRateLimiter struct {
    channelID   string
    rateLimit   int64  // 条数/秒
    windowSize  time.Duration
    store       RateStore  // Redis实现
}

func (r *ChannelRateLimiter) Allow(ctx context.Context) bool {
    key := fmt.Sprintf("channel_rate:%s:%d", r.channelID, time.Now().Unix())
    // INCR + EXPIRE 实现滑动窗口
    count, err := r.store.Incr(ctx, key, r.windowSize)
    if err != nil { return false }
    return count <= r.rateLimit
}

3.7 状态回执与上行

3.7.1 回执处理

func (s *ReportService) HandleReport(ctx context.Context, report *Report) error {
    // 1. 校验消息ID
    msg, err := s.msgStore.Get(ctx, report.MsgID)
    if err != nil {
        return ErrMsgNotFound
    }
    
    // 2. 更新消息状态
    oldStatus := msg.Status
    msg.Status = report.Status
    msg.ReportTime = report.Time
    
    // 3. 计费处理
    if report.Status == Succeed {
        s.balanceService.Confirm(ctx, msg)
    } else {
        s.balanceService.Refund(ctx, msg)
    }
    
    // 4. 更新ClickHouse (状态变更)
    s.asyncWrite.UpdateStatus(ctx, msg)
    
    // 5. 推送回调 (HTTP/CMPP/SMPP)
    s.callbackService.Push(ctx, msg)
    
    // 6. 统计增量 (Redis原子累加)
    s.statsService.Incr(ctx, msg)
    
    return nil
}

3.7.2 推送可靠性

// 推送重试机制 (指数退避)
type CallbackRetry struct {
    MaxRetries int
    Backoff    []time.Duration  // [1s, 2s, 4s, 8s, 16s]
}

// 回执重推任务 (支持30天内)
type ReportRetryTask struct {
    AccountID string
    StartTime time.Time
    EndTime   time.Time
    Status    string
}

4. 数据存储设计

4.1 MySQL 核心表结构

4.1.1 用户表

CREATE TABLE `accounts` (
    `id` VARCHAR(32) PRIMARY KEY,
    `username` VARCHAR(64) UNIQUE NOT NULL,
    `password` VARCHAR(128) NOT NULL,
    `role` TINYINT NOT NULL COMMENT '1-admin 2-客户 3-运维 4-客服',
    `business` SET('sms','video','csp','empty','shorturl') NOT NULL,
    `protocol` SET('http','cmpp','smpp','web') NOT NULL,
    `ip_whitelist` JSON DEFAULT NULL,
    `credit_balance` BIGINT DEFAULT 0 COMMENT '授信余额(分)',
    `balance` BIGINT DEFAULT 0 COMMENT '可用余额(分)',
    `unit_price` INT DEFAULT 0 COMMENT '单价(毫)',
    `audit_mode` TINYINT DEFAULT 0 COMMENT '0免审 1手动 2自动',
    `send_time_start` TIME DEFAULT NULL,
    `send_time_end` TIME DEFAULT NULL,
    `status` TINYINT DEFAULT 1 COMMENT '0禁用 1启用',
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    `deleted_at` DATETIME DEFAULT NULL,
    INDEX idx_status_created (`status`, `created_at`),
    INDEX idx_username (`username`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

4.1.2 通道表

CREATE TABLE `channels` (
    `id` VARCHAR(32) PRIMARY KEY,
    `name` VARCHAR(128) NOT NULL,
    `protocol` VARCHAR(16) NOT NULL COMMENT 'cmpp/http/smpp/sgip',
    `host` VARCHAR(64) NOT NULL,
    `port` INT NOT NULL,
    `username` VARCHAR(64) DEFAULT NULL,
    `password` VARCHAR(128) DEFAULT NULL,
    `enterprise_code` VARCHAR(32) DEFAULT NULL,
    `access_code` VARCHAR(32) DEFAULT NULL,
    `rate_limit` INT DEFAULT 0 COMMENT '条/秒,0不限',
    `day_limit` INT DEFAULT 0 COMMENT '日限,0不限',
    `night_limit` INT DEFAULT 0 COMMENT '夜间限速,条/秒/链',
    `status` TINYINT DEFAULT 1,
    `weight` INT DEFAULT 100,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status_weight (`status`, `weight`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

4.1.3 路由规则表

CREATE TABLE `route_rules` (
    `id` VARCHAR(32) PRIMARY KEY,
    `account_id` VARCHAR(32) DEFAULT NULL COMMENT 'NULL=全局',
    `channel_id` VARCHAR(32) NOT NULL,
    `rule_type` TINYINT NOT NULL COMMENT '1-关键字 2-省份 3-运营商 4-地区',
    `rule_value` VARCHAR(512) NOT NULL,
    `priority` INT DEFAULT 0,
    `weight` INT DEFAULT 100,
    `status` TINYINT DEFAULT 1,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_account_type (`account_id`, `rule_type`),
    INDEX idx_channel (`channel_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

4.1.4 余额变动表

CREATE TABLE `balance_transactions` (
    `id` VARCHAR(32) PRIMARY KEY,
    `account_id` VARCHAR(32) NOT NULL,
    `biz_id` VARCHAR(64) NOT NULL COMMENT '业务单号/消息ID',
    `biz_type` TINYINT NOT NULL COMMENT '1-充值 2-预扣 3-确认 4-退款',
    `amount` BIGINT NOT NULL COMMENT '变动金额(分)',
    `before_balance` BIGINT NOT NULL,
    `after_balance` BIGINT NOT NULL,
    `remark` VARCHAR(256) DEFAULT NULL,
    `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
    INDEX idx_account_created (`account_id`, `created_at`),
    INDEX idx_biz_id (`biz_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

4.2 ClickHouse 明细表

-- 下行明细 (按天分区)
CREATE TABLE sms_down_details ON CLUSTER ck_cluster (
    `msg_id` String,
    `account_id` String,
    `channel_id` String,
    `phone` String,
    `content` String,
    `template_id` String,
    `status` UInt8,
    `error_code` String,
    `send_time` DateTime,
    `report_time` DateTime,
    `fee` UInt16,
    `price` UInt32,
    `province` String,
    `operator` String,
    `signature` String,
    `batch_id` String,
    `ext` String
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/sms_down_details', '{replica}')
PARTITION BY toYYYYMMDD(send_time)
ORDER BY (account_id, send_time, msg_id)
TTL send_time + INTERVAL 180 DAY
SETTINGS index_granularity = 8192;

-- 上行记录
CREATE TABLE sms_up_records ON CLUSTER ck_cluster (
    `msg_id` String,
    `account_id` String,
    `phone` String,
    `content` String,
    `receive_time` DateTime,
    `matched_msg_id` String,
    `channel_id` String,
    `ext` String
) ENGINE = ReplicatedMergeTree('/clickhouse/tables/{shard}/sms_up_records', '{replica}')
PARTITION BY toYYYYMMDD(receive_time)
ORDER BY (account_id, receive_time)
TTL receive_time + INTERVAL 180 DAY;

4.3 Redis 数据结构

Key模式 类型 用途 TTL
balance:{account_id} String 实时余额 持久
frozen:{account_id} String 冻结金额 持久
msg:{msg_id} Hash 消息热数据 5天
user_msg_count:{account_id}:{date} String 日发送计数 30天
channel_rate:{channel_id}:{ts} String 通道限流计数 10s
freq:{phone}:{window} String 频次计数 24h
blacklist:local Set 本地黑名单 持久
whitelist:local Set 白名单 持久
lock:balance:{account_id} String 余额操作锁 5s
session:{token} String 用户会话 2h
route:cache:{account_id} Hash 路由规则缓存 10min
price:cache:{account_id}:{biz} String 价格缓存 5min

5. 高可用与弹性设计

5.1 部署架构

┌────────────────────────────────────────────────────────────────────────┐
│                        负载均衡层 (LVS + Nginx)                          │
│                     VIP: 10.0.0.100 (主备+健康检查)                      │
└────────────────────────────────────────────────────────────────────────┘
                                    │
            ┌───────────────────────┼───────────────────────┐
            │                       │                       │
    ┌───────▼────────┐    ┌───────▼────────┐    ┌───────▼────────┐
    │  AZ-A (主)      │    │  AZ-B (备)      │    │  AZ-C (备)      │
    │  ┌───────────┐  │    │  ┌───────────┐  │    │  ┌───────────┐  │
    │  │ Gateway x3 │  │    │  │ Gateway x3 │  │    │  │ Gateway x3 │  │
    │  │ Business x5│  │    │  │ Business x5│  │    │  │ Business x5│  │
    │  │ Kafka x3   │  │    │  │ Kafka x3   │  │    │  │ Kafka x3   │  │
    │  │ MySQL主    │  │    │  │ MySQL从    │  │    │  │ MySQL从    │  │
    │  │ Redis主    │  │    │  │ Redis从    │  │    │  │ Redis从    │  │
    │  │ CK x2      │  │    │  │ CK x2      │  │    │  │ CK x2      │  │
    │  └───────────┘  │    │  └───────────┘  │    │  └───────────┘  │
    └─────────────────┘    └─────────────────┘    └─────────────────┘

5.2 故障恢复策略

故障场景 恢复策略 RTO RPO
单实例宕机 K8s自动重启 + 服务发现剔除 <30s 0
AZ故障 DNS切流 + Kafka/MySQL主从切换 <5min <1s
MySQL主库故障 MGR自动选主 + 从库提升 <60s <1s
Redis集群故障 哨兵自动切换 <30s <1s
Kafka分区故障 副本自动恢复 <60s 0
消息积压 动态扩消费者 + 限流降级 <5min 0
通道不可用 路由自动切换 + 熔断 <3s 0

5.3 熔断与降级

// 熔断器配置
type CircuitBreakerConfig struct {
    Name          string
    MaxRequests   uint32        // 半开状态最大请求数
    Interval      time.Duration // 统计窗口
    Timeout       time.Duration // 超时时间
    FailureRate   float64       // 失败率阈值 (0-1)
    RequestVolume uint32        // 最小请求量
}

// 降级策略
type DegradeStrategy interface {
    ShouldDegrade(ctx context.Context) bool
    Fallback(ctx context.Context, req interface{}) (interface{}, error)
}

// 实现: BalanceDegrade (余额降级-只读), RouteDegrade (路由降级-默认通道)

6. 性能优化设计

6.1 并发模型

// 协程池配置 (基于ants)
type PoolConfig struct {
    WorkerSize    int   // 工作协程数: CPU核心数 * 2
    MaxBlocking   int   // 最大阻塞任务数: 10000
    NonBlocking   bool  // 非阻塞模式
    ExpiryDuration time.Duration // 空闲回收: 10s
}

// 业务隔离: 不同业务使用独立协程池
// 1. 发送池: 高优先级, 大容量
// 2. 回执池: 中优先级
// 3. 统计池: 低优先级, 批量处理
// 4. 审计池: 低优先级, 异步写

6.2 缓存策略

cache_strategy:
  # 本地缓存 (LRU)
  local:
    capacity: 10000
    ttl: 60s
    items:
      - price:price_*           # 价格缓存
      - account:account_*       # 账号信息
      - channel:channel_*       # 通道信息
      - route:route_*           # 路由规则

  # Redis缓存 (多级)
  redis:
    # 热数据 (5天)
    hot_data:
      ttl: 5d
      max_keys: 10000000
    # 计数 (滑动窗口)
    counter:
      ttl: 24h
    # 分布式锁
    lock:
      ttl: 5s
      retry: 3

6.3 批量处理优化

// 批量聚合写入 ClickHouse
type BatchWriter struct {
    buffer    []*Message
    size      int           // 10000条
    interval  time.Duration // 5秒
    mu        sync.Mutex
    cond      *sync.Cond
}

// CMPP 合包发送 (聚合提交)
type CMPPSubmitAggregator struct {
    buffer   map[string]*CMPPSubmitReq  // 按通道聚合
    size     int                         // 1000包/批次
    interval time.Duration               // 5秒
}

6.4 数据库连接池

database:
  mysql:
    max_open_conns: 100
    max_idle_conns: 20
    conn_max_lifetime: 3600s
    conn_max_idle_time: 600s
  clickhouse:
    max_open_conns: 50
    max_idle_conns: 10
    conn_max_lifetime: 1800s

7. 监控与可观测性

7.1 关键指标

类别 指标 采集方式 告警阈值
业务 发送成功率 回执统计 <95%
发送量QPS 网关计数 >20000
通道不可用率 心跳检测 >5%
余额预警 定时检查 低于阈值
审核积压 定时统计 >1000条
系统 API响应P99 Prometheus >100ms
CPU利用率 Node Exporter >80%
内存利用率 Node Exporter >85%
GC暂停时间 Go Runtime >10ms
Goroutine数量 Go Runtime >100000
协程池利用率 业务埋点 >90%
中间件 Redis命中率 Redis Info <90%
Kafka消费Lag Kafka Metrics >10000
MySQL慢查询 MySQL Slow Log >100ms
ClickHouse写入延迟 业务埋点 >100ms

7.2 日志体系

// 结构化日志 (Zap)
logger.Info("message submitted",
    zap.String("msg_id", msgID),
    zap.String("account_id", accountID),
    zap.String("phone", phone),
    zap.Int64("fee", fee),
    zap.Duration("latency", time.Since(start)),
)

// 日志分类
// 1. access.log  - 访问日志 (ELK)
// 2. app.log     - 应用日志 (ELK)
// 3. error.log   - 错误日志 (ELK + 钉钉告警)
// 4. audit.log   - 审计日志 (ES, 保留180天)
// 5. slow.log    - 慢请求日志 (>100ms)

7.3 分布式追踪

// OpenTelemetry集成
func TracingMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        tracer := otel.Tracer("gateway")
        ctx, span := tracer.Start(c.Request.Context(), c.Request.URL.Path)
        defer span.End()
        
        // 注入TraceID到日志
        logger := logger.With(
            zap.String("trace_id", span.SpanContext().TraceID().String()),
        )
        c.Set("logger", logger)
        c.Set("ctx", ctx)
        c.Next()
    }
}

8. 安全设计

8.1 鉴权与授权

// JWT Token
type Claims struct {
    AccountID  string   `json:"aid"`
    Username   string   `json:"un"`
    Roles      []string `json:"roles"`
    Permissions []string `json:"perms"`
    jwt.RegisteredClaims
}

// 权限中间件 (Casbin)
func (s *SecurityService) Authorize(ctx context.Context, accountID, resource, action string) bool {
    // 1. 获取用户角色
    roles := s.GetRoles(ctx, accountID)
    // 2. Casbin策略检查
    // 3. 二级权限检查 (充值/代发/导出)
    return s.enforcer.Enforce(roles, resource, action)
}

8.2 数据安全

安全措施 实现方式
传输加密 TLS 1.3 + 证书自动轮换
敏感数据加密 AES-256 (账号密码/API密钥)
SQL注入防护 GORM参数化查询 + 预编译
XSS防护 Gin模板自动转义
审计日志 记录所有敏感操作 (登录/充值/删除)
IP白名单 接口客户强制校验
权限最小化 RBAC + 二级权限控制

9. 部署与运维

9.1 容器化部署

# Dockerfile
FROM golang:1.22-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o gateway ./cmd/server

FROM alpine:latest
RUN apk --no-cache add ca-certificates tzdata
COPY --from=builder /app/gateway /app/gateway
COPY --from=builder /app/configs /app/configs
WORKDIR /app
EXPOSE 8080
ENTRYPOINT ["./gateway"]

9.2 Kubernetes资源配置

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: go-sms-gateway
  namespace: go-sms
spec:
  replicas: 3
  selector:
    matchLabels:
      app: hwsms-gateway
  template:
    metadata:
      labels:
        app: hwsms-gateway
    spec:
      containers:
      - name: gateway
        image: hwsms/gateway:latest
        ports:
        - containerPort: 8080
        resources:
          requests:
            memory: "512Mi"
            cpu: "500m"
          limits:
            memory: "2Gi"
            cpu: "2"
        env:
        - name: POD_IP
          valueFrom:
            fieldRef:
              fieldPath: status.podIP
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 30
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 10
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: hwsms-gateway
spec:
  selector:
    app: hwsms-gateway
  ports:
  - name: http
    port: 8080
    targetPort: 8080
  - name: cmpp
    port: 7890
    targetPort: 7890
  type: ClusterIP
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: hwsms-gateway-hpa
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: hwsms-gateway
  minReplicas: 3
  maxReplicas: 20
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70
  - type: Resource
    resource:
      name: memory
      target:
        type: Utilization
        averageUtilization: 80

9.3 CI/CD流水线

# .gitlab-ci.yml
stages:
  - test
  - build
  - deploy

test:
  stage: test
  script:
    - go test -v -race -cover ./...
    - go vet ./...

build:
  stage: build
  script:
    - docker build -t $CI_REGISTRY/hwsms/gateway:$CI_COMMIT_SHA .
    - docker push $CI_REGISTRY/hwsms/gateway:$CI_COMMIT_SHA

deploy-dev:
  stage: deploy
  script:
    - kubectl set image deployment/hwsms-gateway gateway=$CI_REGISTRY/hwsms/gateway:$CI_COMMIT_SHA -n hwsms-dev
    - kubectl rollout status deployment/hwsms-gateway -n hwsms-dev
  environment: dev

deploy-prod:
  stage: deploy
  script:
    - kubectl set image deployment/hwsms-gateway gateway=$CI_REGISTRY/hwsms/gateway:$CI_COMMIT_SHA -n hwsms-prod
    - kubectl rollout status deployment/hwsms-gateway -n hwsms-prod
  environment: prod
  when: manual

10. 容量规划

10.1 估算基准

场景 日均量 峰值QPS 数据增长/天
短信发送 5000万条 20000 5000万行
上行记录 500万条 2000 500万行
回执处理 5000万条 20000 5000万行
用户数 5000个 - -
通道数 200个 - -

10.2 存储估算

数据类型 单条大小 日增量 180天总量 存储方案
下行明细 200字节 10GB 1.8TB ClickHouse (压缩后~600GB)
上行记录 150字节 750MB 135GB ClickHouse
业务数据 - 10MB 1.8GB MySQL
日志数据 - 20GB 3.6TB ES (30天)
文件存储 - 5GB 900GB MinIO/OSS

10.3 资源规划

组件 节点数 规格 总资源
Gateway 3-20 (HPA) 4C 8G 动态
Business 5-30 (HPA) 4C 8G 动态
MySQL 1主2从 16C 64G 96C 192G
Redis 6节点 (3主3从) 8C 32G 48C 192G
Kafka 3节点 8C 32G + 2TB SSD 24C 96G
ClickHouse 2分片×2副本 16C 64G + 4TB SSD 64C 256G
ES 3节点 8C 32G + 2TB SSD 24C 96G

10.4 通道吞吐规划(当前部署口径:下家接收 5000 TPS / 上家下发 3000 TPS)

远期口径见 10.1(日 5000 万、峰值 2 万);本节为当前单通道部署的工程落地口径,数字均有 Day39 真网实测背书(logs/bench-day39/,累计 10 万条零失败零断链)。

10.4.1 下发能力实测基线(CMPP 2.0,16 连接)

在途窗口 均值 TPS 峰值 TPS p50 p90 p99 边际产出
64(4/连接) 1023 1178 40.1ms 116ms 375ms 18.4 TPS/窗口
160(10/连接) 1836 2573 46.1ms 194ms 510ms 11.5 TPS/窗口
256(16/连接) 2263 3203 52.2ms 301ms 510ms 8.8 TPS/窗口

结论:上家宣称 3000 TPS 为峰值口径(实测峰值 3203 ✓);持续吞吐 ≈2200~2300(256 窗口均值),边际递减明显。p50 上升(28→40→52ms)是下游饱和拐点信号。若业务需均值 3000 持续,须与通道方确认提高连接配额(>16)或服务端扩容(P1 待办)。

10.4.2 一收一发容量数据流

客户(下家) ──5000 TPS──▶ gateway×2~3(HPA) ──▶ Redis(鉴权/预扣Lua/双桶限流)
  (接收能力)                    │  同步链路≤5ms,严禁 MySQL 直写
                                ▼
                      Kafka sms-submit (16分区, key=channel_id)
                                │  ← 削峰缓冲:净积压 2000/s×5min=60万条≈600MB
                                ▼
                     consumer worker ──▶ MySQL 批量落库(异步,500条/批)
                                ▼
                per-channel dispatcher: 令牌桶=channel.speed(默认3000)
                + 在途窗口 256 (16连接×16, 10.4.1 实测背书)
                                ▼ ──3000 TPS(峰值)──▶ 上家 CMPP Pool

10.4.3 各层容量要点

层 目标 设计 推算依据
入口(HTTP/CMPP 接入) 5000 TPS gateway 2~3 副本 4C8G + HPA(CPU 70%);同步链路=Redis 鉴权 0.5ms+校验内存级+预扣 Lua 1ms+Kafka acks=1 约 1ms 35ms/条 → 单副本 20004000 TPS
中间件(Kafka) 缓冲 5000 入/3000 出 sms-submit 16 分区(312 TPS/分区) key=channel_id;sms-report 16 分区 key=detail_id;副本 2、幂等 producer、重试+DLQ 单分区顺序写 ~1000 TPS 安全;key 保证通道级顺序与回执配对
中间件(Redis) 限流/预扣/黑名单 双桶令牌桶(全局 5000+账号 speed_limit)、预扣 Lua 原子、滑动窗口频次 全部 O(1) 命令,单集群 10 万+ ops/s
数据层(MySQL) 5000 行/s 写 明细只走 consumer 批量 INSERT(500 条/批 × 10 并发 writer=10 批/s);回执按 detail_id 批量 UPDATE ... IN (500);message_detail 按天分区、热 5 天 批量写使 InnoDB redo/索引压力降 2 个数量级;单条直写 5000/s 必死
数据层(ClickHouse) 明细归档 批量 1 万行/flush;5 天后从 MySQL 迁出 技术方案 10.2 既有口径
下发(dispatcher) 峰值 3000 令牌桶=channel.speed + 窗口 256;p50>50ms 持续 30s 自动降速 10% 10.4.1;压测证实 p50 上升=饱和

10.4.4 背压分级(5000 入 − 3000 出 = 净积压 2000/s)

水位 触发条件 动作
L1 告警 submit lag > 10 万(满速积压 ~50s) 告警通知,投放器降速
L2 收紧 lag > 100 万 或持续 10 分钟净增 入口全局限流收紧至 Σ(通道 speed),超额返回 429/流控错误码
L3 降级 lag > 500 万 或通道熔断 暂停低优先级群发任务,仅保验证/通知类;客户公告

群发大任务由匀速投放器按下游预算逐秒投放(每秒 min(剩余, Σ通道speed−在途余量)),不瞬时打满队列。


11. 项目结构

hwsms/
├── cmd/
│   ├── gateway/          # 网关服务
│   │   └── main.go
│   ├── business/          # 业务服务
│   │   └── main.go
│   ├── scheduler/         # 调度服务
│   │   └── main.go
│   └── consumer/          # 消费者服务
│       └── main.go
├── internal/
│   ├── api/              # API定义
│   │   ├── gateway/      # 网关API
│   │   ├── business/     # 业务API
│   │   └── proto/        # gRPC Proto
│   ├── service/          # 业务服务实现
│   │   ├── account/
│   │   ├── channel/
│   │   ├── send/
│   │   ├── route/
│   │   ├── audit/
│   │   ├── balance/
│   │   ├── report/
│   │   ├── stats/
│   │   ├── settlement/
│   │   └── notification/
│   ├── repository/       # 数据访问层
│   │   ├── mysql/
│   │   ├── redis/
│   │   ├── clickhouse/
│   │   └── es/
│   ├── model/            # 数据模型
│   │   ├── entity/
│   │   ├── dto/
│   │   └── vo/
│   ├── middleware/       # 中间件
│   │   ├── auth/
│   │   ├── ratelimit/
│   │   ├── logger/
│   │   ├── tracer/
│   │   └── recovery/
│   ├── protocol/         # 协议实现
│   │   ├── cmpp/
│   │   ├── smpp/
│   │   ├── sgip/
│   │   └── http/
│   ├── router/           # 路由引擎
│   ├── config/           # 配置管理
│   ├── util/             # 工具函数
│   │   ├── id.go         # 雪花ID
│   │   ├── crypto.go     # 加密解密
│   │   └── validator.go  # 校验器
│   └── pkg/              # 内部共享包
│       ├── logger/
│       ├── metrics/
│       ├── queue/        # 消息队列封装
│       ├── cache/        # 缓存封装
│       └── lock/         # 分布式锁
├── configs/              # 配置文件
│   ├── dev/
│   ├── staging/
│   └── prod/
├── scripts/              # 脚本
│   ├── init.sql
│   ├── migration/
│   └── deploy/
├── deployments/          # K8s配置
│   ├── base/
│   └── overlays/
├── test/                 # 测试
│   ├── unit/
│   ├── integration/
│   └── e2e/
├── docs/                 # 文档
├── go.mod
├── go.sum
├── Makefile
└── README.md

12. 关键代码示例

12.1 雪花ID生成器

package util

import (
    "sync"
    "time"
)

type Snowflake struct {
    mu        sync.Mutex
    timestamp int64
    workerID  int64
    sequence  int64
    epoch     int64
}

func NewSnowflake(workerID int64) *Snowflake {
    return &Snowflake{
        workerID: workerID,
        epoch:    1640995200000, // 2022-01-01
        sequence: 0,
    }
}

func (s *Snowflake) NextID() int64 {
    s.mu.Lock()
    defer s.mu.Unlock()
    
    now := time.Now().UnixMilli()
    if now == s.timestamp {
        s.sequence = (s.sequence + 1) & 4095
        if s.sequence == 0 {
            for now <= s.timestamp {
                now = time.Now().UnixMilli()
            }
        }
    } else {
        s.sequence = 0
    }
    s.timestamp = now
    
    return ((now - s.epoch) << 22) | (s.workerID << 12) | s.sequence
}

12.2 分布式锁 (Redis)

package lock

import (
    "context"
    "time"
    "github.com/go-redis/redis/v9"
)

type RedisLock struct {
    client *redis.Client
    key    string
    value  string
    ttl    time.Duration
}

func (l *RedisLock) Lock(ctx context.Context) (bool, error) {
    return l.client.SetNX(ctx, l.key, l.value, l.ttl).Result()
}

func (l *RedisLock) Unlock(ctx context.Context) error {
    script := `
        if redis.call("get", KEYS[1]) == ARGV[1] then
            return redis.call("del", KEYS[1])
        else
            return 0
        end
    `
    _, err := l.client.Eval(ctx, script, []string{l.key}, l.value).Result()
    return err
}

12.4 限流器 (令牌桶)

package ratelimit

import (
    "context"
    "sync"
    "time"
)

type TokenBucket struct {
    mu       sync.Mutex
    rate     float64   // 令牌填充速率
    capacity float64   // 桶容量
    tokens   float64
    lastTime time.Time
}

func (tb *TokenBucket) Allow() bool {
    tb.mu.Lock()
    defer tb.mu.Unlock()
    
    now := time.Now()
    elapsed := now.Sub(tb.lastTime).Seconds()
    tb.tokens += elapsed * tb.rate
    if tb.tokens > tb.capacity {
        tb.tokens = tb.capacity
    }
    tb.lastTime = now
    
    if tb.tokens >= 1 {
        tb.tokens--
        return true
    }
    return false
}

13. 总结

本技术方案基于Go语言构建,核心设计要点:

  1. 高可用:多AZ部署、故障自动切换、数据多副本、熔断降级
  2. 低延时:多级缓存(Caffeine+Redis)、连接池复用、非阻塞I/O、P99<50ms
  3. 高并发:协程池管控、Kafka削峰填谷、水平弹性扩展、10万QPS支撑
  4. 可观测:Prometheus监控、Jaeger链路追踪、ELK日志聚合
  5. 可扩展:微服务架构、配置热加载、插件化路由引擎

关键风险与应对:

  • MySQL热数据压力 → 5天热窗口 + Redis缓存 + 读写分离
  • 回执风暴 → Kafka分区扩容 + 批量聚合写入ClickHouse
  • 通道故障 → 路由自动切换 + 熔断隔离
  • 数据一致性 → 分布式事务(Saga模式) + 幂等设计
  • 大文件处理 → MinIO异步存储 + 任务队列

建议实施路径:

  1. 第1-2月:基础架构搭建 + 核心P0功能
  2. 第3-4月:路由引擎 + 计费系统
  3. 第5-6月:通道接入 + 回执系统
  4. 第7-8月:P1运营支撑功能
  5. 第9-10月:P2增值业务 + 性能调优
  6. 第11-12月:全面测试 + 灰度发布 + 上线