目录

Visit Stat - 访问统计系统

基于 HyperLogLog 实现的高性能 UV 统计系统,支持 TTL 过期,采用 gokv2 + redcon 作为 Redis 兼容存储。

技术栈

  • 后端: Gin + go-redis
  • KV 存储: gokv2 + redcon (Redis 兼容服务器)
  • 前端: Vinext (Next.js API on Vite)
  • 存储: gokv2 (KV) + HyperLogLog (UV 统计)

项目结构

visit-stat/
├── main.go                    # Gin HTTP 服务入口
├── kvserver.exe              # Redis 兼容服务器 (gokv2 + redcon)
├── go.mod                    # Go 依赖
├── README.md                 # 项目文档
├── cmd/kvserver/            # KV 服务器
│   └── main.go
├── internal/
│   ├── cache/
│   │   ├── redis.go        # Redis 接口定义
│   │   └── redis_client.go # go-redis 客户端实现
│   ├── handler/
│   │   └── handler.go      # HTTP 接口
│   └── stat/
│       └── visit.go         # 统计服务
└── frontend/                # 前端 (Vinext)
    ├── app/
    ├── vite.config.ts
    └── package.json

功能特性

  • UV 统计: 使用 HyperLogLog 实现高性能去重统计
  • TTL 支持: 自动过期清理,节省存储空间
  • Redis 兼容: 可用 redis-cli 直接访问
  • 接口抽象: Redis 接口设计,方便替换存储实现

快速开始

1. 启动 KV 服务器 (Redis 兼容)

./kvserver.exe

默认监听 localhost:6399

2. 启动 HTTP 后端

./visit-stat.exe

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

3. 启动前端

cd frontend
pnpm install
pnpm dev

前端默认在 http://localhost:5173 启动

使用 redis-cli 测试

redis-cli -p 6399

# 测试 SET/GET
127.0.0.1:6399> SET mykey "hello"
OK
127.0.0.1:6399> GET mykey
"hello"

# 测试 HyperLogLog
127.0.0.1:6399> PFADD uv:test "user1"
(integer) 1
127.0.0.1:6399> PFADD uv:test "user2"
(integer) 1
127.0.0.1:6399> PFCOUNT uv:test
(integer) 2

API 接口

方法 路径 说明
POST /api/visit 记录访问
GET /api/stat/total 总 UV
GET /api/stat/daily?date=2026-03-01 日 UV
GET /api/stat/hourly?hour=2026-03-01-15 小时 UV
GET /api/stat/uv?days=7 多日 UV 统计

设计说明

Redis 接口抽象

internal/cache/redis.go 定义了 Redis 接口:

type Redis interface {
    Set(ctx context.Context, key string, value interface{}, expiration time.Duration) error
    Get(ctx context.Context, key string) (string, error)
    PFAdd(ctx context.Context, key string, elements ...string) error
    PFCount(ctx context.Context, keys ...string) (int64, error)
    // ...
}

如需替换为真正 Redis,只需实现该接口即可。

TTL 过期机制

  • 每日统计 key 有效期: 24 小时
  • 每小时统计 key 有效期: 2 小时
  • 后台 goroutine 每秒检查并清理过期 key
关于
113.0 KB
邀请码
    Gitlink(确实开源)
  • 加入我们
  • 官网邮箱:gitlink@ccf.org.cn
  • QQ群
  • QQ群
  • 公众号
  • 公众号

版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9 京公网安备 11010802032778号