|
|
@ -3,7 +3,6 @@ package sqlx
|
|
|
|
import (
|
|
|
|
import (
|
|
|
|
"database/sql"
|
|
|
|
"database/sql"
|
|
|
|
"io"
|
|
|
|
"io"
|
|
|
|
"sync"
|
|
|
|
|
|
|
|
"time"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
|
|
"github.com/zeromicro/go-zero/core/syncx"
|
|
|
|
"github.com/zeromicro/go-zero/core/syncx"
|
|
|
@ -17,43 +16,29 @@ const (
|
|
|
|
|
|
|
|
|
|
|
|
var connManager = syncx.NewResourceManager()
|
|
|
|
var connManager = syncx.NewResourceManager()
|
|
|
|
|
|
|
|
|
|
|
|
type pingedDB struct {
|
|
|
|
func getCachedSqlConn(driverName, server string) (*sql.DB, error) {
|
|
|
|
*sql.DB
|
|
|
|
|
|
|
|
once sync.Once
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
func getCachedSqlConn(driverName, server string) (*pingedDB, error) {
|
|
|
|
|
|
|
|
val, err := connManager.GetResource(server, func() (io.Closer, error) {
|
|
|
|
val, err := connManager.GetResource(server, func() (io.Closer, error) {
|
|
|
|
conn, err := newDBConnection(driverName, server)
|
|
|
|
conn, err := newDBConnection(driverName, server)
|
|
|
|
if err != nil {
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return &pingedDB{
|
|
|
|
return conn, nil
|
|
|
|
DB: conn,
|
|
|
|
|
|
|
|
}, nil
|
|
|
|
|
|
|
|
})
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return val.(*pingedDB), nil
|
|
|
|
return val.(*sql.DB), nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func getSqlConn(driverName, server string) (*sql.DB, error) {
|
|
|
|
func getSqlConn(driverName, server string) (*sql.DB, error) {
|
|
|
|
pdb, err := getCachedSqlConn(driverName, server)
|
|
|
|
conn, err := getCachedSqlConn(driverName, server)
|
|
|
|
if err != nil {
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
pdb.once.Do(func() {
|
|
|
|
return conn, nil
|
|
|
|
err = pdb.Ping()
|
|
|
|
|
|
|
|
})
|
|
|
|
|
|
|
|
if err != nil {
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
return pdb.DB, nil
|
|
|
|
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
func newDBConnection(driverName, datasource string) (*sql.DB, error) {
|
|
|
|
func newDBConnection(driverName, datasource string) (*sql.DB, error) {
|
|
|
@ -70,5 +55,10 @@ func newDBConnection(driverName, datasource string) (*sql.DB, error) {
|
|
|
|
conn.SetMaxOpenConns(maxOpenConns)
|
|
|
|
conn.SetMaxOpenConns(maxOpenConns)
|
|
|
|
conn.SetConnMaxLifetime(maxLifetime)
|
|
|
|
conn.SetConnMaxLifetime(maxLifetime)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if err := conn.Ping(); err != nil {
|
|
|
|
|
|
|
|
_ = conn.Close()
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return conn, nil
|
|
|
|
return conn, nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|