为租户提供一键导出 Excel 并支持流式下载

解读

国内 B 端 SaaS 普遍采用“多租户共享数据库、独立 schema”或“独立库”模式。面试官问“一键导出 Excel 并流式下载”,核心想验证四点:

  1. 是否理解“租户数据隔离”——SQL 层面必须带 tenant_id,防止越权。
  2. 是否理解“大文件场景”——万行级、十万行级甚至百万行级数据,不能一次性 load 到内存,否则 OOM。
  3. 是否理解“流式”——HTTP 1.1 chunked 或 HTTP/2 stream,边查边写边压缩,首包响应 <200 ms,用户体验“秒弹下载框”。
  4. 是否理解“Beego 生态”——路由、中间件、context、responseWriter 的正确用法,以及框架自身对 gzip、cache、timeout 的默认行为。

一句话:让面试官相信,给你 1000 万行数据,你也能在 4C8G 容器里 30 秒导出且不爆内存。

知识点

  1. 租户隔离:
    • 数据层:每条业务表必备 tenant_id,索引 (tenant_id, create_time) 覆盖查询。
    • 代码层:Beego 的 Prepare() 钩子统一注入 ctx.Input.GetData("tenantId")。
  2. 流式写 Excel:
    • 选型:excelize 的 NewStreamWriter(),或 tealeg/xlsx 的 StreamFileBuilder;官方压测 10 万行 * 20 列 ≈ 60 MB,内存峰值 < 80 MB。
    • 模式:for rows.Next() → scan → sw.SetRow() → flush;每 2000 行显式 Flush(),防止缓冲区膨胀。
  3. HTTP 响应:
    • Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
    • Content-Disposition: attachment; filename*=UTF-8''订单_20250625_{{.TenantId}}.xlsx
    • 关闭 Beego 默认 gzip(SetLevel(0)),避免双重压缩浪费 CPU。
  4. 异步与重试:
    • 超过 30 秒走“异步导出 + 文件服务器”方案:Beego task 队列生成文件 → 回调通知 → 前端轮询或 WebSocket 推送下载链接。
  5. 资源保护:
    • 接口限流:令牌桶 5 次/分钟/租户,防止“刷爆”。
    • 查询超时:context.WithTimeout(2 * time.Minute),MySQL 层 max_execution_time=120000。
  6. 监控:
    • Prometheus 埋点:export_duration_seconds、export_rows_total、export_fail_total,标签 tenant_id。

答案

下面给出可直接落地的最小可运行版本(十万行内同步流式导出,更大请改用异步方案)。

// routers/router.go
func init() {
    web.Router("/api/v1/orders/export", &controllers.OrderController{}, "get:Export")
}

// controllers/order.go
type OrderController struct {
    web.Controller
}

func (c *OrderController) Export() {
    tenantId, ok := c.Ctx.Input.GetData("tenantId").(int64)
    if !ok || tenantId <= 0 {
        c.CustomAbort(400, "非法租户")
    }
    // 1. 组装查询
    db := models.GetDB() // 返回带 tenant_id 的 gorm.DB
    query := db.Model(&models.Order{}).Where("tenant_id = ?", tenantId).
        Select("order_no, amount, status, created_at").
        Order("created_at desc")

    // 2. 提前写响应头,触发流式
    c.Ctx.Output.Header("Content-Type", 
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
    c.Ctx.Output.Header("Content-Disposition", 
        fmt.Sprintf(`attachment; filename*=UTF-8''订单_%s_%d.xlsx`, 
            time.Now().Format("20060102"), tenantId))
    c.Ctx.Output.Header("Transfer-Encoding", "chunked")
    // 关闭 Beego 默认 gzip
    c.Ctx.Output.Header("Content-Encoding", "")

    // 3. 新建流式 Excel
    file := excelize.NewFile()
    sw, err := file.NewStreamWriter("Sheet1")
    if err != nil {
        c.CustomAbort(500, "创建流式写入器失败")
    }
    // 写表头
    head := []interface{}{"订单号", "金额(元)", "状态", "创建时间"}
    if err := sw.SetRow("A1", head); err != nil {
        c.CustomAbort(500, "写表头失败")
    }

    // 4. 分页流式查询
    var (
        rows      []models.Order
        pageSize  = 2000
        offset    = 0
        rowIndex  = 2
    )
    for {
        if err := query.Limit(pageSize).Offset(offset).Find(&rows).Error; err != nil {
            c.CustomAbort(500, "查询数据失败")
        }
        if len(rows) == 0 {
            break
        }
        // 写数据
        for _, r := range rows {
            data := []interface{}{r.OrderNo, r.Amount, r.Status, r.CreatedAt.Format("2006-01-02 15:04:05")}
            cell, _ := excelize.CoordinatesToCellName(1, rowIndex)
            if err := sw.SetRow(cell, data); err != nil {
                c.CustomAbort(500, "写行失败")
            }
            rowIndex++
        }
        offset += pageSize
    }

    // 5.  flush 并关闭流式写入器
    if err := sw.Flush(); err != nil {
        c.CustomAbort(500, "flush 失败")
    }
    // 6. 直接写到 http.ResponseWriter
    if _, err := file.WriteTo(c.Ctx.ResponseWriter); err != nil {
        logs.Error("write excel error: %v", err)
    }
}

关键点回顾

  • 全程无 rows = append(rows, …),内存占用 O(1)。
  • 使用 Transfer-Encoding: chunked,浏览器实时弹出下载框。
  • 若数据量>30 万行,把“写文件”动作放到 Beego task 里,生成后上传到 OSS,再返回 302 重定向,避免长连接占用。

拓展思考

  1. 多语言表头:把表头做成 i18n 配置,根据租户语言字段动态切换。
  2. 动态列:租户后台勾选“导出列”,后端把列配置序列化成 JSON 存 Redis,导出时动态拼装 select 字段与表头。
  3. 增量导出:利用“上次导出位点”字段(redis key = tenant:export:offset)做游标,下次只导 > offset 的数据,实现“差异导出”。
  4. 压缩与分卷:单文件 > 200 MB 时,用 zip 分卷 100 MB/卷,前端多线程并行下载,提升弱网成功率。
  5. 安全加固:
    • 下载链接加一次性签名(JWT + 过期时间 5 分钟),防止 URL 被转发泄露。
    • 敏感字段脱敏:金额>1 万打码“123**.00”,手机号中间四位星号。
  6. 云原生:
    • 容器设置 resources.requests.memory=1Gi,limits.memory=2Gi,导出 Pod 与业务 Pod 分离,避免相互影响。
    • 使用 K8s HPA,根据 export_duration_seconds 指标自动扩容导出服务。