Go语言实现权重抽奖系统

案例:Go语言实现权重抽奖系统

需求描述

  1. 支持配置多个奖品及对应权重
  2. 保证抽奖结果符合权重概率分布
  3. 防止重复中奖
  4. 提供抽奖结果验证接口

完整实现代码

go 复制代码
package main

import (
	"crypto/rand"
	"encoding/json"
	"fmt"
	"math/big"
	"net/http"
	"sync"
)

// 奖品配置
type Prize struct {
	ID     int    `json:"id"`
	Name   string `json:"name"`
	Weight int    `json:"weight"` // 权重值(非百分比)
}

// 抽奖系统
type LotterySystem struct {
	prizes       []Prize
	totalWeight  int
	issuedPrizes map[int]bool
	mu           sync.Mutex
}

// 初始化抽奖系统
func NewLotterySystem(prizes []Prize) *LotterySystem {
	total := 0
	for _, p := range prizes {
		total += p.Weight
	}
	return &LotterySystem{
		prizes:       prizes,
		totalWeight:  total,
		issuedPrizes: make(map[int]bool),
	}
}

// 安全随机数生成
func secureRandom(max int) (int, error) {
	n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
	if err != nil {
		return 0, err
	}
	return int(n.Int64()), nil
}

// 执行抽奖
func (ls *LotterySystem) Draw() (*Prize, error) {
	ls.mu.Lock()
	defer ls.mu.Unlock()

	if ls.totalWeight == 0 {
		return nil, fmt.Errorf("no available prizes")
	}

	// 生成随机数
	randomNum, err := secureRandom(ls.totalWeight)
	if err != nil {
		return nil, err
	}

	// 权重选择
	current := 0
	for _, p := range ls.prizes {
		current += p.Weight
		if randomNum < current {
			if ls.issuedPrizes[p.ID] {
				continue // 已发放的奖品跳过
			}
			ls.issuedPrizes[p.ID] = true
			return &p, nil
		}
	}

	return nil, fmt.Errorf("draw failed")
}

// HTTP服务
func main() {
	// 初始化奖品池
	prizes := []Prize{
		{ID: 1, Name: "一等奖", Weight: 1},
		{ID: 2, Name: "二等奖", Weight: 5},
		{ID: 3, Name: "三等奖", Weight: 20},
		{ID: 4, Name: "参与奖", Weight: 74},
	}

	lottery := NewLotterySystem(prizes)

	http.HandleFunc("/draw", func(w http.ResponseWriter, r *http.Request) {
		prize, err := lottery.Draw()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		json.NewEncoder(w).Encode(prize)
	})

	fmt.Println("抽奖服务已启动,监听端口 8080")
	http.ListenAndServe(":8080", nil)
}

核心功能说明

  1. 权重算法
go 复制代码
// 权重选择逻辑
current := 0
for _, p := range ls.prizes {
    current += p.Weight
    if randomNum < current {
        return &p
    }
}
  • 使用累计权重区间算法
  • 保证概率分布准确性
  1. 安全随机数
go 复制代码
// 使用crypto/rand生成安全随机数
func secureRandom(max int) (int, error) {
    n, err := rand.Int(rand.Reader, big.NewInt(int64(max)))
    // ...
}
  • 避免使用math/rand的可预测性
  • 满足安全抽奖需求
  1. 并发控制
go 复制代码
var mu sync.Mutex

func (ls *LotterySystem) Draw() {
    ls.mu.Lock()
    defer ls.mu.Unlock()
    // ...
}
  • 使用互斥锁保证线程安全
  • 防止并发抽奖导致的数据竞争
  1. 防重复机制
go 复制代码
issuedPrizes map[int]bool
  • 使用内存映射记录已发放奖品
  • 生产环境可替换为Redis等持久化存储

扩展功能建议

  1. 概率可视化验证
go 复制代码
// 添加测试端点验证概率分布
http.HandleFunc("/test", func(w http.ResponseWriter, r *http.Request) {
    results := make(map[int]int)
    for i := 0; i < 10000; i++ {
        tempLottery := NewLotterySystem(prizes)
        prize, _ := tempLottery.Draw()
        results[prize.ID]++
    }
    json.NewEncoder(w).Encode(results)
})
  1. 分布式锁扩展
go 复制代码
// 使用Redis分布式锁
func (ls *LotterySystem) DistributedDraw() {
    lock := redis.NewLock("lottery_lock")
    err := lock.Lock()
    // ...抽奖逻辑...
    lock.Unlock()
}
  1. 奖品库存管理
go 复制代码
type Prize struct {
    // ...
    Stock     int // 新增库存字段
}

func (ls *LotterySystem) Draw() {
    // 检查库存
    if p.Stock <= 0 {
        continue
    }
    // 扣减库存
    p.Stock--
}

运行测试

  1. 启动服务:
bash 复制代码
go run main.go
  1. 测试抽奖:
bash 复制代码
curl http://localhost:8080/draw
# 示例返回:{"id":3,"name":"三等奖","weight":20}
  1. 概率验证测试:
bash 复制代码
curl http://localhost:8080/test
# 返回万次抽奖结果分布

关键优化点

  1. 性能优化
  • 使用预计算总权重值
  • 内存级锁粒度控制
  • 对象池复用
  1. 安全增强
  • JWT用户身份验证
  • 抽奖频率限制
  • 敏感操作日志
  1. 业务扩展
  • 支持不同抽奖活动
  • 奖品有效期管理
  • 中奖名单公示
相关推荐
颜酱1 小时前
06 | 把 meta_config 同步进 MySQL(生成阶段)
前端·人工智能·后端
IT_陈寒2 小时前
SpringBoot自动配置坑了我一周,原来问题这么蠢!
前端·人工智能·后端
iOS开发上架哦3 小时前
Android代码混淆与iOS加固技术详解
后端·ios
Alan_6914 小时前
商品详情优化三板斧-拆分-多级缓存-GC调参
后端·缓存
Conan在掘金4 小时前
ArkTS 进阶之道(3):为哈禁解构声明?类型一眼可见 vs 推断链断裂
后端
晚安code4 小时前
干掉成山的 if-else:工厂造、策略选,一文讲透两个模式的配合
后端·设计模式
feng尘4 小时前
深度解析布隆过滤器(Bloom Filter):原理、优缺点与 1000 万黑名单实战
后端·面试
大陈AI4 小时前
Docker Compose 前后端部署踩坑实录:3 个坑让我的容器反复 Exit(1)
后端
长大19884 小时前
MySQL 慢查询排查完整流程
后端
苏三说技术4 小时前
为什么越来越多人使用FastAPI?
后端