连接池学习
This commit is contained in:
35
connectPool/goroutine/readgo.go
Normal file
35
connectPool/goroutine/readgo.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package goroutine
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Dataread(db *sql.DB, donetitle chan struct{}) {
|
||||
// 启动一个长事务(整个循环在一个事务内,而非每次查询一个事务)
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer tx.Rollback() // 确保退出时回滚(仅为测试)
|
||||
|
||||
// 随机种子(保持不变)
|
||||
rand.Seed(time.Now().UnixNano())
|
||||
|
||||
// 只执行两次查询,方便观察结果
|
||||
for i := 0; i < 2; i++ {
|
||||
select {
|
||||
case <-time.After(2 * time.Second): // 第一次查询后等待2秒,给Datawrite插入时间
|
||||
var count int
|
||||
err = tx.QueryRow("SELECT count(*) FROM article WHERE age > 50 FOR UPDATE ").Scan(&count)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
fmt.Printf("第%d次查询 count: %d\n", i+1, count)
|
||||
case <-donetitle:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user