当前位置:网站首页>Design of golang lottery system
Design of golang lottery system
2022-07-26 03:01:00 【Upper back left love】
Business difficulties
Design a lottery system , This system is not materialized , It's abstraction , It has the following difficulties :
1、 Lottery business needs Complicated and changeable
2、 Prize type and probability setting
3、 Fair draw and safe Award
4、 Concurrent security issues One cannot shoot many times
5、 Efficient draw and Award , Provide high concurrency and performance
6、 How to use redies To optimize
Technology options
- High concurrency Go Collaboration takes precedence over PHP Multi process ,Java Of Multithreading model
- High performance compiled binary takes precedence over PHP Explanatory and Java virtual machine
- Efficient network model epoll The model takes precedence over PHPBIO Models and Java NIO Model
sweepstakes
- The annual meeting draw , Lottery scratch , Wechat shakes , Lottery turntable , Activities such as lucky card , This project
Lottery turntableDesign as an activity . - Actual content of the project : frame / Core code background function , Set and send prizes reasonably , mysql+ Optimize - Use redies Award plan and prize pool , Stress testing and more operational strategies ( Have a better understanding of the performance of the system , There are more strategies for operating products ), introduce thirft frame (RPC frame ), Design interface generation code , Server interface and client program
Demand analysis
1. go mod To configure
2. Configure domestic agents : go env -w GOPROXY=https://goproxy.cn,https://goproxy.io,direct
3. go get -u -v github.com/kataras/iris The download package is in GOPATH Of PKG Under the table of contents
4. iris: function : Safety certification , cache cookies file MVC, Templates Rich sample code
5. https://iris-go.com/v10/recipe
* The drawing process of the annual meeting
It uses iris This web frame To deal with
/** * curl http://localhost:8080/ * curl --data "users=123,567" http://localhost:8080/import * curl http://localhost:8080/lucky */
package main
import (
"fmt"
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
"math/rand"
"strings"
"sync"
"time"
)
var userList []string // Before and after reading and writing shared variables Need to increase the Lock setting Add mutexes in a simple way
var mu sync.Mutex
type lotteryController struct {
Ctx iris.Context
}
// Start a iris application
func newApp() *iris.Application {
app := iris.New()
mvc.New(app.Party("/")).Handle(&lotteryController{
})
return app
}
func main() {
app := newApp()
userList = []string{
}
mu = sync.Mutex{
}
err := app.Listen(":8080")
if err != nil {
panic(fmt.Sprintf("web server start error: %s\n", err))
return
}
}
func (c *lotteryController) Get() string {
count := len(userList)
return fmt.Sprintf(" The current total number of users participating in the lottery :%d\n", count)
}
// PostImport POST http://localhost:8090/import
// params : users
func (c *lotteryController) PostImport() string {
strUsers := c.Ctx.FormValue("users")
users := strings.Split(strUsers, ",")
// When batch threads are imported Found a problem with multithreading The statistics are incorrect
mu.Lock()
defer mu.Unlock()
count1 := len(userList)
for _, u := range users {
u = strings.TrimSpace(u)
if len(u) > 0 {
userList = append(userList, u)
}
}
count2 := len(userList)
return fmt.Sprintf(" The current total number of users participating in the lottery :%d, Number of users successfully imported :%d\n", count2, count2-count1)
}
// GetLucky GET http://localhost:8090/lucky
func (c *lotteryController) GetLucky() string {
// The lottery place carries on the lock judgment
mu.Lock()
defer mu.Unlock()
count := len(userList)
if count > 1 {
index := rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(int32(count))
user := userList[index]
// need Delete the selected person You can delete At present index The data under the Better
userList = append(userList[0:index], userList[index+1:]...)
return fmt.Sprintf(" Current winning users :%s, Number of remaining users :%d\n", user, count-1)
} else if count == 1 {
user := userList[0]
return fmt.Sprintf(" Current winning users :%s, Number of remaining users :%d\n", user, count-1)
} else {
return fmt.Sprintf(" The current winning is over , No user participated in winning \n")
}
}
Unit test problems , about userList Of Data contention occurs in multithreading :
package main
import (
"fmt"
"github.com/kataras/iris/v12/httptest"
"sync"
"testing"
)
func TestMVC(t *testing.T) {
app := newApp()
e := httptest.New(t, app)
// Use synchronous wait lock
var wg sync.WaitGroup
e.GET("/").Expect().Status(httptest.StatusOK).Body().Equal(" The current total number of users participating in the lottery :0\n")
for i := 0; i < 100; i++ {
wg.Add(1)
// There will be no concurrency problem
go func(i int) {
defer wg.Done()
e.POST("/import").WithFormField("users", fmt.Sprintf("test_u%d", i)).Expect().Status(httptest.StatusOK)
}(i)
}
wg.Wait()
e.GET("/").Expect().Status(httptest.StatusOK).Body().Equal(" The current total number of users participating in the lottery :100\n")
e.GET("/lucky").Expect().Status(httptest.StatusOK)
e.GET("/").Expect().Status(httptest.StatusOK).Body().Equal(" The current total number of users participating in the lottery :99\n")
}
边栏推荐
- 手把手教你依赖管理
- After clicking play, the variables in editorwindow will be destroyed inexplicably
- 图像识别(七)| 池化层是什么?有什么作用?
- What if the test / development programmer gets old? Lingering cruel facts
- Literature speed reading | in the face of danger, anxious people run faster?
- Pinia plugin persist, a data persistence plug-in of Pinia
- The El table header merges the first four columns into one cell
- [reading notes] user portrait methodology and engineering solutions
- Case: using kept+haproxy to build a Web Cluster
- AMD64 (x86_64) architecture ABI document:
猜你喜欢

ES6高级-利用构造函数继承父类属性

HLS Experiment 1 -- multiplier

Simply use MySQL index

图像识别(六)| 激活函数

ES6高级-利用原型对象继承方法

C language layered understanding (C language function)

1. Software testing ----- the basic concept of software testing

规范自己debug的流程

中国信通院陈屹力:降本增效是企业云原生应用的最大价值

From the annual reports of major apps, we can see that user portraits - labels know you better than you do
随机推荐
Teach you to rely on management hand in hand
[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)
massCode 一款优秀的开源代码片段管理器
【C语言】深入理解 整型提升 和 算术转换
一切的源头,代码分支策略的选择
eslint常见报错集合
对于稳定性测试必需关注的26点
JVM内存模型解析
MySQL build websites data table
Machine learning foundation plan 0-2: what is machine learning? What does it have to do with AI?
Neo4j 导入csv数据报错:Neo4j load csv error : Couldn‘t load the external resource
File operation (I) -- File introduction and file opening and closing methods
Longest Substring Without Repeating Characters
【C进阶】深入探索数据的存储(深度剖析+典例解读)
当点击Play以后,EditorWindow中的变量会被莫名其妙销毁.
MySQL教程:MySQL数据库学习宝典(从入门到精通)
重装Win7系统如何进行?
(九)属性自省
Win11大小写提示图标怎么关闭?Win11大小写提示图标的关闭方法
Article setting top