【GO+Iris】实战-高并发抽奖系统

【GO+Iris】实战-高并发抽奖系统,第1张

前言 一、场景二、抽奖系统业务难点三、抽奖系统技术挑战四、技术选型 GO vs PHP/JAVA五、内容概览 && 前置知识前置知识开发环境学习建议 六、抽奖活动Demo年会抽奖程序-annualMeeting初级版本 TODO...待续

一、场景

二、抽奖系统业务难点

需求复杂又多变
奖品类型和概率设置
如何公平的抽奖、安全的发奖

三、抽奖系统技术挑战

网络并发编程、数据读写的并发安全性问题
高效的抽奖和发奖,提高并发和性能
系统优化,怎么吧redis更好的利用起来

四、技术选型 GO vs PHP/JAVA

高并发,GO协程优于PHP多线程,JAVA多线程模式
高性能,编译后的二进制优于PHP解释型、JAVA虚拟机
高效网络模型,epoll优于PHP的BIO、JAVA的NIO

五、内容概览 && 前置知识


前置知识

1、GO语法基本知识,基本的设计和项目实践经验
2、了解和接触过抽奖系统或者类似的活动
3、网络并发编程、分布式集群系统的设计和开发

开发环境

1、Go1.10以上,iris、xorm、thrift等包文件
2、依赖的MySQL5.5/redis3.0以上服务
3、Goland编辑器教程/macOS

学习建议

免费课:https://www.imooc.com/learn/1066 讲解iris 以及 xorm 应用

关注一凡Sir的手记文章,内容是关于高性能、高并发及网络编程等

课前思考,课后总结以及多问为什么

六、抽奖活动Demo 年会抽奖程序-annualMeeting

需求:导入全公司员工名单,每次随即抽取一个人
未知:有一等奖、二等奖等、也有一些领导临时加的奖品
年会奖品不涉及并发,但抽奖程序要考虑并发的可能

初级版本
package main

import (
	"fmt"
	"math/rand"
	"strings"
	"time"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

var (
	userList []string // 全局用户列表
)

// 初始化一个对象
type lotteryController struct {
	Ctx iris.Context
}

// GET http://localhost:8080
// curl http://localhost:8080
// GetUsers
func (c *lotteryController) GetUsers() string {
	content := len(userList)
	return fmt.Sprintf("抽奖人数 %d", content)
}

// POST http://localhost:8080/import
// params: users
// curl  --data "users=yifan,yifan2,zhangsan" http://localhost:8080/import
// PostImport
func (c *lotteryController) PostImport() string {
	strUsers := c.Ctx.FormValue("users")
	users := strings.Split(strUsers, ",")

	count1 := len(users)
	for _, item := range users {
		item = strings.TrimSpace(item)
		if len(item) > 0 {
			userList = append(userList, item)
		}
	}
	count2 := len(userList)
	return fmt.Sprintf("抽奖人数 %d,导入人数 %d", count2, count1)
}

// GET http://localhost:8080/lucky
// curl http://localhost:8080/lucky
// GetLucky
func (c *lotteryController) GetLucky() string {
	count := len(userList)
	if count == 1 {
		user := userList[0]
		userList = []string{}
		return fmt.Sprintf("当前中奖用户:%s,剩余用户数目:%d", user, count-1)
	} else if count > 1 {
		seed := time.Now().UnixNano()
		index := rand.New(rand.NewSource(seed)).Int31n(int32(count))
		user := userList[index]
		userList = append(userList[0:index], userList[index+1:]...)
		return fmt.Sprintf("当前中奖用户:%s,剩余用户数目:%d", user, count-1)
	} else {
		return fmt.Sprintf("当前没有中奖用户,请重新输入待抽选名单")
	}
}

// newApp
func newApp() *iris.Application {
	app := iris.New()
	mvc.New(app.Party("/")).Handle(&lotteryController{})
	return app
}

func main() {
	// 初始化
	app := newApp()
	userList = []string{}

	// 启动监听
	app.Run(iris.Addr(":8080"))
	return
}

运行效果:

TODO…待续

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/995513.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-21
下一篇 2022-05-21

发表评论

登录后才能评论

评论列表(0条)

保存