You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
935 B
43 lines
935 B
package sqlx |
|
|
|
import ( |
|
"database/sql" |
|
"git.diulo.com/mogfee/kit/core/syncx" |
|
"io" |
|
"time" |
|
) |
|
|
|
const ( |
|
maxIdleConns = 64 |
|
maxOpenConns = 64 |
|
maxLifetime = time.Minute |
|
) |
|
|
|
var connManager = syncx.NewResourceManager() |
|
|
|
func getCachedSqlConn(driverName string, server string) (*sql.DB, error) { |
|
val, err := connManager.GetResource(server, func() (io.Closer, error) { |
|
return newDBConnection(driverName, server) |
|
}) |
|
if err != nil { |
|
return nil, err |
|
} |
|
return val.(*sql.DB), nil |
|
} |
|
|
|
func getSqlConn(driverName, server string) (*sql.DB, error) { |
|
return getCachedSqlConn(driverName, server) |
|
} |
|
func newDBConnection(driverName, datasource string) (*sql.DB, error) { |
|
conn, err := sql.Open(driverName, datasource) |
|
if err != nil { |
|
return nil, err |
|
} |
|
conn.SetMaxIdleConns(maxIdleConns) |
|
conn.SetMaxOpenConns(maxOpenConns) |
|
conn.SetConnMaxLifetime(maxLifetime) |
|
if err = conn.Ping(); err != nil { |
|
return nil, err |
|
} |
|
return conn, nil |
|
}
|
|
|