package main import ( "database/sql" "log" "strconv" "sync" "time" "github.com/Pallinder/go-randomdata" _ "github.com/go-sql-driver/mysql" ) func GetConnect(port int) *sql.DB { mysqluri := "root:yame123456@tcp(localhost:" + strconv.Itoa(port) + ")/yame" db, err := sql.Open("mysql", mysqluri) if err != nil { panic(err) } err = db.Ping() if err != nil { panic(err) } return db } func DBUpdate(db *sql.DB, names []string) { now := time.Now() N := 1 for i := 0; i < N; i++ { for _, name := range names { tx, err := db.Begin() if err != nil { panic(err) } age := strconv.Itoa(randomdata.Number(0, 105)) level := strconv.Itoa(randomdata.Number(0, 10)) attr := randomdata.Address() tx.Exec("update user set age = ?, level = ?, attr = ? where name = ?", age, level, attr, name) err = tx.Commit() if err != nil { panic(err) } } } log.Println(int64(len(names)*N)/(time.Now().Unix()-now.Unix()), " update qps") } func Task(port int, wg *sync.WaitGroup) { defer wg.Done() db := GetConnect(port) DBUpdate(db, RandomSelectNames(db)) } func RandomSelectNames(db *sql.DB) []string { var names []string COUNT := 10 for i := 0; i < COUNT; i++ { age := randomdata.Number(0, 105) taskid := randomdata.Number(0, 1000) offset := randomdata.Number(0, 100) rows, err := db.Query("select * from (select name from user where taskid = ? and age = ? limit 1000 OFFSET ?)t1 order by rand() ", taskid, age, offset) if err != nil { panic(err) } for rows.Next() { var name string rows.Scan(&name) names = append(names, name) } } log.Println(len(names)) return names } func Updating() { gcount := 1 wg := &sync.WaitGroup{} wg.Add(gcount) for i := 0; i < gcount; i++ { go Task(3306, wg) } // DBInsert(23306) wg.Wait() log.Println("gthread: ", gcount) }