forked from bachvtuan/Golang-Mongodb-Transaction-Example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmultiple_queue_transfer.go
229 lines (170 loc) · 5.79 KB
/
multiple_queue_transfer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
/**
* This is the example code demonstrate transaction about transfer money between accounts in system.
* Test condition: the total balance of all users before and after transfer should have the same amount.
*/
package main
import (
"strconv"
"io"
"net/http"
"fmt"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
"math/rand"
"time"
"sync"
)
var global_db *mgo.Database
var mu = &sync.Mutex{}
//Get random number from range [ min, max ]
func Random(min, max int) int {
rand.Seed(time.Now().UTC().UnixNano())
return rand.Intn(max - min + 1) + min
}
type Currency struct {
Id bson.ObjectId `json:"id" bson:"_id,omitempty"`
Amount float64 `bson:"amount"`
Account string `bson:"account"`
Code string `bson:"code"`
}
var countTrasaction = 0
var maxUser = 100
var maxThread = 10
//Array of channels input and output
var in []chan Transaction
var out []chan Result
type Transaction struct{
Source string
Target string
}
type Result struct{
Account string
Result string
}
func transfer(w http.ResponseWriter, r *http.Request) {
// random user from 1 to maxUser
number := Random( 1, maxUser )
//Allocate to appropriate channel number based on number by get the last number in the random number.
channelNumber := number % maxThread
sourceAccount := "user" + strconv.Itoa( number )
targetNumber := Random( 1, maxUser )
if targetNumber == number{
io.WriteString(w, "ignore because same account")
return
}
targetAccount := "user" + strconv.Itoa( targetNumber )
var wg sync.WaitGroup
wg.Add(1)
go func () {
in[ channelNumber ] <- Transaction{ Source: sourceAccount, Target: targetAccount }
for {
select {
case result := <- out[ channelNumber ]:
if result.Account == sourceAccount{
/*fmt.Printf("Result %s\n", result.Result)
fmt.Printf("Number is %d \n", channelNumber )*/
fmt.Printf("Result %s and countTrasaction is %d\n", result.Result, countTrasaction)
io.WriteString(w, result.Result)
wg.Done()
//should return, otherwise it's still pop out value from out channel
return
}else{
fmt.Printf("Dismatch: %s and %s\n", result.Account, sourceAccount)
panic("why ?, Something went wrong")
//push to out again
out[ channelNumber ] <- result
}
};
}
}()
wg.Wait()
}
func main() {
in = make([]chan Transaction, maxThread)
out = make([]chan Result, maxThread)
for i := range in {
fmt.Printf("i %d \n", i )
in[i] = make(chan Transaction)
out[i] = make(chan Result)
}
session, _ := mgo.Dial("localhost:27017")
fmt.Printf("Session is %p\n", session)
global_db = session.DB( "db_log" )
//make sure it is empty first
global_db.C("bank").DropCollection()
//Init maxUser with amount are 1000USD.
for i := 1; i <= maxUser; i++ {
user := Currency{ Account : "user" + strconv.Itoa( i ) , Amount: 1000.00, Code:"USD" }
err := global_db.C("bank").Insert(&user)
if err != nil{
panic("insert error")
}
}
fmt.Printf("len in is %d", len( in ))
fmt.Printf("len out is %d", len( out ))
//Create 10 go routine to handle for each channel
for i := range in {
go func ( subIn *chan Transaction, index int ) {
for {
select{
case transaction := <-*subIn:
account := transaction.Source
fmt.Printf("On worker %d \n", index + 1)
/*count_queue += 1
fmt.Printf("count_queue %d\n", count_queue)*/
entry := Currency{}
err := global_db.C("bank").Find(bson.M{"account": account }).One(&entry)
if err != nil {
panic(err)
}
if entry.Amount < 50.00 {
out[ index ] <- Result{ Account: account, Result: "out_of_balance"}
}else{
// Decrease balance from source account
/**
* Should not use this code to update
* entry.Amount = entry.Amount - 50.00
* err = global_db.C("bank").UpdateId(entry.Id, entry)
* Because maybe other go routine are handle this source account the target account.
*/
colQuerier := bson.M{"account": transaction.Source }
change := bson.M{"$inc": bson.M{"amount": -50 }}
err = global_db.C("bank").Update(colQuerier, change)
if err != nil {
out[ index ] <- Result{ Account: account, Result: "update error"}
}
// Increase balance to target account
colQuerier = bson.M{"account": transaction.Target }
change = bson.M{"$inc": bson.M{"amount": 50 }}
err = global_db.C("bank").Update(colQuerier, change)
if err != nil {
out[ index ] <- Result{ Account: account, Result: "update error"}
}
countTrasaction = countTrasaction + 1
fmt.Printf("countTrasaction %d\n", countTrasaction)
out[ index ] <- Result{ Account: account, Result: fmt.Sprintf("countTrasaction %d\n", countTrasaction)}
}
}
}
}(&in[i], i)
}
http.HandleFunc("/", transfer)
http.ListenAndServe(":8000", nil)
}
/*
How to test this code works:
After init: we can use this command to show the total amount of all users.
db.getCollection('bank').aggregate(
[
{
$group:
{
_id: null,
totalAmount: { $sum: "$amount" },
count: { $sum: 1 }
}
}
]
)
After run the concurrency test, we should run that command too. If the totalAmount is same, This code works because the total balances is integrity.
*/