local-development.md 9.8 KB

本地开发调试指南

概述

本文档提供了物联网基站管理系统的本地开发环境搭建和调试步骤,帮助开发者快速搭建开发环境并进行本地调试。

环境要求

基础环境

  • Go: 1.19 或更高版本
  • Docker: 20.10 或更高版本
  • Docker Compose: 2.0 或更高版本
  • Git: 最新版本

开发工具(推荐)

  • IDE: VS Code / GoLand
  • 数据库工具: DBeaver / pgAdmin
  • API测试: Postman / Insomnia
  • MQTT客户端: MQTT Explorer / mosquitto_pub/sub

环境搭建

1. 克隆项目

git clone https://github.com/your-username/iot-base-station.git
cd iot-base-station

2. 安装Go依赖

go mod download
go mod tidy

3. 启动基础服务

使用Docker Compose启动数据库、缓存等基础服务:

# 启动基础服务(不包括应用)
docker-compose up -d postgres influxdb redis nats mqtt

# 查看服务状态
docker-compose ps

4. 等待服务就绪

等待所有服务启动完成,可以通过以下命令检查:

# 检查PostgreSQL
docker-compose logs postgres | grep "database system is ready"

# 检查InfluxDB
curl -s http://localhost:8086/health

# 检查Redis
docker-compose exec redis redis-cli ping

# 检查NATS
curl -s http://localhost:8222/varz

# 检查MQTT
docker-compose exec mqtt mosquitto_sub -h localhost -t '$SYS/#' -C 1

本地开发配置

1. 创建开发配置文件

创建一个开发专用的配置文件:

cp config/config.yaml config/config.dev.yaml

编辑 config/config.dev.yaml,修改以下配置:

server:
  port: "8080"
  mode: "debug"  # 开发模式

database:
  postgres:
    host: "localhost"
    port: "5432"
    user: "postgres"
    password: "postgres"
    dbname: "iot_base_station"
  
  influxdb:
    url: "http://localhost:8086"
    token: "dev-token"
    org: "iot-org"
    bucket: "iot-data"

redis:
  host: "localhost"
  port: "6379"

nats:
  url: "nats://localhost:4222"

mqtt:
  broker: "tcp://localhost:1883"
  client_id: "iot-gateway-dev"

logging:
  level: "debug"
  output: "stdout"  # 输出到控制台

2. 初始化数据库

创建数据库初始化脚本:

# 创建PostgreSQL数据库
docker-compose exec postgres psql -U postgres -c "CREATE DATABASE iot_base_station;"

# 运行数据库迁移
go run cmd/migrate/main.go up

3. 配置环境变量

创建 .env 文件:

# .env
CONFIG_PATH=config/config.dev.yaml
GIN_MODE=debug

本地运行

1. 运行主服务器

# 方式1:直接运行
go run cmd/server/main.go

# 方式2:使用环境变量
CONFIG_PATH=config/config.dev.yaml go run cmd/server/main.go

# 方式3:使用Air热重载(推荐)
air -c .air.toml

2. 运行数据网关

# 新终端窗口
go run cmd/gateway/main.go

3. 运行监控服务

# 新终端窗口
go run cmd/monitor/main.go

4. 运行设备模拟器

# 新终端窗口
go run simulations/main.go -broker=tcp://localhost:1883 -count=5 -interval=30s

调试技巧

1. 使用Delve调试器

安装Delve调试器:

go install github.com/go-delve/delve/cmd/dlv@latest

启动调试会话:

# 调试主服务器
dlv debug cmd/server/main.go

# 调试特定函数
dlv debug --headless --listen=:2345 --api-version=2 cmd/server/main.go

在VS Code中配置调试:

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Launch Server",
      "type": "go",
      "request": "launch",
      "mode": "debug",
      "program": "${workspaceFolder}/cmd/server/main.go",
      "env": {
        "CONFIG_PATH": "config/config.dev.yaml"
      }
    },
    {
      "name": "Launch Gateway",
      "type": "go",
      "request": "launch",
      "mode": "debug",
      "program": "${workspaceFolder}/cmd/gateway/main.go",
      "env": {
        "CONFIG_PATH": "config/config.dev.yaml"
      }
    }
  ]
}

2. 日志调试

在代码中添加调试日志:

import "go.uber.org/zap"

// 在函数中添加调试日志
logger.Debug("Processing device data", 
    zap.String("device_id", deviceID),
    zap.Any("data", data))

3. 性能分析

启用性能分析:

import (
    _ "net/http/pprof"
    "net/http"
)

// 在main函数中添加
go func() {
    log.Println(http.ListenAndServe("localhost:6060", nil))
}()

访问性能分析页面:

4. 数据库调试

使用DBeaver连接PostgreSQL:

  • 主机: localhost
  • 端口: 5432
  • 数据库: iot_base_station
  • 用户名: postgres
  • 密码: postgres

使用InfluxDB Web UI:

测试

1. 运行单元测试

# 运行所有测试
go test ./...

# 运行特定包的测试
go test ./internal/device

# 运行测试并生成覆盖率报告
go test -coverprofile=coverage.out ./...
go tool cover -html=coverage.out

2. 运行集成测试

# 运行集成测试
go test -tags=integration ./tests/integration/...

# 运行端到端测试
go test -tags=e2e ./tests/e2e/...

3. API测试

使用Postman导入API集合:

  1. 打开Postman
  2. 导入 docs/postman_collection.json
  3. 设置环境变量:

使用curl测试:

# 注册设备
curl -X POST http://localhost:8080/api/v1/devices \
  -H "Content-Type: application/json" \
  -d '{
    "name": "测试温度传感器",
    "type": "temperature_sensor",
    "protocol": "mqtt",
    "metadata": {
      "location": "机房A"
    }
  }'

# 获取设备列表
curl -X GET http://localhost:8080/api/v1/devices

# 获取实时数据
curl -X GET "http://localhost:8080/api/v1/data/realtime?device_id=temp_sensor_01"

常见问题

1. 端口冲突

如果遇到端口冲突,可以修改配置文件中的端口设置:

server:
  port: "8081"  # 修改为其他端口

或者停止占用端口的进程:

# 查找占用端口的进程
lsof -i :8080

# 停止进程
kill -9 <PID>

2. 数据库连接失败

检查数据库服务状态:

docker-compose logs postgres

确保数据库配置正确:

database:
  postgres:
    host: "localhost"  # 如果使用Docker,可能需要改为host.docker.internal

3. MQTT连接失败

检查MQTT服务状态:

docker-compose logs mqtt

使用MQTT客户端测试连接:

# 订阅主题
docker-compose exec mqtt mosquitto_sub -h localhost -t "iot/data/+/+"

# 发布消息
docker-compose exec mqtt mosquitto_pub -h localhost -t "iot/data/test/temperature" -m '{"temperature": 25.5}'

4. 依赖问题

如果遇到依赖问题,尝试重新安装:

# 清理模块缓存
go clean -modcache

# 重新下载依赖
go mod download

# 整理依赖
go mod tidy

开发工具

1. 热重载

安装Air热重载工具:

go install github.com/cosmtrek/air@latest

创建 .air.toml 配置文件:

root = "."
testdata_dir = "testdata"
tmp_dir = "tmp"

[build]
  args_bin = []
  bin = "./tmp/main"
  cmd = "go build -o ./tmp/main ./cmd/server"
  delay = 1000
  exclude_dir = ["assets", "tmp", "vendor", "testdata"]
  exclude_file = []
  exclude_regex = ["_test.go"]
  exclude_unchanged = false
  follow_symlink = false
  full_bin = ""
  include_dir = []
  include_ext = ["go", "tpl", "tmpl", "html"]
  kill_delay = "0s"
  log = "build-errors.log"
  send_interrupt = false
  stop_on_root = false

[color]
  app = ""
  build = "yellow"
  main = "magenta"
  runner = "green"
  watcher = "cyan"

[log]
  time = false

[misc]
  clean_on_exit = false

2. 代码格式化

安装gofmt和golint:

go install golang.org/x/tools/cmd/goimports@latest
go install golang.org/x/lint/golint@latest

配置VS Code自动格式化:

{
  "go.useLanguageServer": true,
  "go.formatTool": "goimports",
  "go.lintTool": "golint",
  "go.lintOnSave": "package",
  "editor.formatOnSave": true,
  "editor.codeActionsOnSave": {
    "source.organizeImports": true
  }
}

3. Git钩子

安装pre-commit钩子:

# 安装pre-commit
pip install pre-commit

# 创建.pre-commit-config.yaml
pre-commit install

.pre-commit-config.yaml 内容:

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-added-large-files

  - repo: https://github.com/tekwizely/pre-commit-golang
    rev: v1.0.0-rc.1
    hooks:
      - id: go-fmt
      - id: go-vet-mod
      - id: go-mod-tidy

性能优化

1. 数据库优化

  • 添加适当的索引
  • 使用连接池
  • 优化查询语句

2. 内存优化

  • 使用对象池
  • 避免内存泄漏
  • 监控内存使用

3. 并发优化

  • 使用goroutine池
  • 避免竞态条件
  • 使用channel进行通信

部署准备

1. 构建生产版本

# 构建二进制文件
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o bin/server cmd/server/main.go
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o bin/gateway cmd/gateway/main.go
CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o bin/monitor cmd/monitor/main.go

2. 创建Docker镜像

# 构建镜像
docker build -t iot-base-station:latest .

# 推送到镜像仓库
docker push your-registry/iot-base-station:latest

3. 配置生产环境

创建生产环境配置文件 config/config.prod.yaml,设置生产环境参数。

通过以上步骤,您应该能够成功搭建物联网基站管理系统的本地开发环境,并进行有效的调试和开发工作。