Skip to content

Latest commit

 

History

History
149 lines (116 loc) · 3.89 KB

File metadata and controls

149 lines (116 loc) · 3.89 KB

快速开始

最后更新:2026-04-24

返回文档索引


前置条件

  • Go 1.24+
  • Docker & Docker Compose
  • PostgreSQL 16 客户端(可选)

环境搭建

1. 克隆项目

git clone https://github.com/your-org/tokenrouter.git
cd tokenrouter

2. 安装依赖

# 后端依赖
go mod download

3. 配置环境变量

cp .env.example .env
# 编辑 .env,填入必要的配置

关键配置项:

# 数据库
DATABASE_URL=postgres://tokenrouter:password@localhost:5432/tokenrouter?sslmode=disable
REDIS_URL=redis://localhost:6379/0

# API Keys(上游 Provider)
# MVP v0.1 只需 DeepSeek Key,其余预留 Phase 1.1
DEEPSEEK_API_KEY=sk-xxx
# OPENAI_API_KEY=sk-xxx
# ANTHROPIC_API_KEY=sk-ant-xxx

# 功能开关
CACHE_INJECT_ENABLED=true      # Anthropic cache_control 注入(预留接口,v0.1 不生效)
DEDUP_ENABLED=true             # 非流式去重
RATE_LIMIT_ENABLED=true        # 速率限制

# 服务配置
PORT=8080
LOG_LEVEL=info

4. 启动依赖服务

docker compose -f deployments/docker-compose.yml up -d

启动的服务:

  • PostgreSQL 16 (端口 5432)
  • Redis 7 (端口 6379)
  • Prometheus (端口 9090)
  • Grafana (端口 3000)

5. 启动开发服务器

数据库迁移在服务启动时自动执行(golang-migrate 使用编译进二进制的嵌入式迁移文件)。

make dev
# 或手动启动
go run cmd/server/main.go

服务启动在 http://localhost:8080

验证

# 健康检查
curl http://localhost:8080/health

# 发送测试请求(需要先创建 API Key)
curl -X POST http://localhost:8080/v1/chat/completions \
  -H "Authorization: Bearer tr-test-xxx" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-chat",
    "messages": [{"role": "user", "content": "Hello"}],
    "stream": false
  }'

项目结构速览

tokenrouter/
├── cmd/server/          # 程序入口
├── internal/
│   ├── inbound/         # 入站适配层
│   ├── envelope/        # 统一内部格式
│   ├── block/           # Block 定义
│   ├── chunker/         # 分块器(策略层)
│   ├── arranger/        # 排列器(结构层)
│   ├── canonicalizer/   # 序列化规范器(物理层)
│   ├── cacheinject/     # 缓存注入器
│   ├── hasher/          # 前缀/完整哈希计算
│   ├── dedup/           # 请求去重器
│   ├── observer/        # 流量观测(Phase 2)
│   ├── outbound/        # 出站适配层
│   ├── proxy/           # 流式代理
│   ├── billing/         # 计费与配额
│   ├── monitor/         # 监控指标采集
│   ├── middleware/      # 认证、限流中间件
│   └── model/           # 数据模型
├── pkg/                 # 公共工具包
├── migrations/          # 数据库迁移
├── deployments/         # Docker/K8s 部署配置
└── docs/                # 技术文档

常用命令

make dev             # 启动开发服务器(自动指定本地 migrations 路径)
make build           # 编译二进制
make test            # 运行测试(mock-based)
make test-e2e-fast   # 真实 API 快速验证(需 DEEPSEEK_API_KEY)
make test-e2e-full   # 真实 API 全量验证(上线前)
make lint            # 代码检查
make migrate         # 只执行数据库迁移(需 DATABASE_URL)
make seed            # 说明 seed 定价由 migrations/006_seed_pricing.up.sql 完成
make docker-up       # 启动 Docker 依赖
make docker-down     # 停止 Docker 依赖

下一步