-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
119 lines (100 loc) · 2.11 KB
/
main.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
package main
import (
"database/sql"
_ "github.com/lib/pq"
"log"
"sync"
"time"
)
var (
db *sql.DB
mutex sync.Mutex
)
const (
dsn = `host=192.168.1.138 port=4932 dbname=postgres user=postgres password=admin sslmode=disable`
)
func init() {
mutex.Lock()
defer mutex.Unlock()
if db != nil {
return
}
// open
pdb, err := sql.Open("postgres", dsn)
if err != nil {
panic("sql.Open: " + err.Error())
}
// 删除表
_, err = pdb.Exec(`drop table if exists tb_user`)
if err != nil {
log.Println("db.Exec: ", err.Error())
return
}
// 创建表
_, err = pdb.Exec(`create table if not exists tb_user(id serial primary key not null, name text, create_time timestamp(0) without time zone default current_timestamp)`)
if err != nil {
log.Println("pdb.Exec: ", err.Error())
return
}
// 开启最大连接数
pdb.SetMaxIdleConns(10000)
db = pdb
}
func main() {
// 开启事务
var err error
tx, err := db.Begin()
if err != nil {
log.Println("db.Begin: ", err.Error())
return
}
defer func() {
if err != nil && tx != nil {
// 回滚
if err := tx.Rollback(); err != nil {
log.Println("tx.Rollback: ", err.Error())
return
}
}
}()
// 编译sql语句
// TODO:预编译一定要放在全局,防止sql语句重新编译
stmt, err := tx.Prepare(`insert into tb_user(id, name, create_time) values($1, 'viney', default)`)
if err != nil {
log.Println("tx.Prepare: ", err.Error())
return
}
defer func() {
if err = stmt.Close(); err != nil {
log.Println("stmt.Close: ", err.Error())
return
}
}()
finish := make(chan bool)
count := 10000
t := time.Now()
for i := 0; i < count; i++ {
go func(i int) {
defer func() { finish <- true }()
// 执行sql语句
if _, err = stmt.Exec(i); err != nil {
log.Println("stmt.Exec: ", err.Error())
return
}
}(i)
}
for i := 0; i < count; i++ {
<-finish
}
log.Println(time.Now().Sub(t))
// 提交事务
if err = tx.Commit(); err != nil {
log.Println("tx.Commit: ", err.Error())
return
}
// 关闭数据库连接
if err = db.Close(); err != nil {
log.Println("db.Close: ", err.Error())
return
}
}