ent 基本使用十一 sql.DB 集成

這個功能是github中你們提的比較多的一個,因此官方也暴露了相關的apimysql

配置sql.DB

  • 一種方式
package main
import (
    "time"
    "<your_project>/ent"
    "github.com/facebookincubator/ent/dialect/sql"
)
func Open() (*ent.Client, error) {
    drv, err := sql.Open("mysql", "<mysql-dsn>")
    if err != nil {
        return nil, err
    }
    // Get the underlying sql.DB object of the driver.
    db := drv.DB()
    db.SetMaxIdleConns(10)
    db.SetMaxOpenConns(100)
    db.SetConnMaxLifetime(time.Hour)
    return ent.NewClient(ent.Driver(drv)), nil
}
 
 
  • 第二種方式
package main
import (
    "database/sql"
    "time"
    "<your_project>/ent"
    entsql "github.com/facebookincubator/ent/dialect/sql"
)
func Open() (*ent.Client, error) {
    db, err := sql.Open("mysql", "<mysql-dsn>")
    if err != nil {
        return nil, err
    }
    db.SetMaxIdleConns(10)
    db.SetMaxOpenConns(100)
    db.SetConnMaxLifetime(time.Hour)
    // Create an ent.Driver from `db`.
    drv := entsql.OpenDB("mysql", db)
    return ent.NewClient(ent.Driver(drv)), nil
}
 

集成監控

方便分析sqlgit

package main
import (
    "context"
    "database/sql"
    "database/sql/driver"
    "<project>/ent"
    "contrib.go.opencensus.io/integrations/ocsql"
    "github.com/go-sql-driver/mysql"
    entsql "github.com/facebookincubator/ent/dialect/sql"
)
type connector struct {
    dsn string
}
func (c connector) Connect(context.Context) (driver.Conn, error) {
    return c.Driver().Open(c.dsn)
}
func (connector) Driver() driver.Driver {
    return ocsql.Wrap(
        mysql.MySQLDriver{},
        ocsql.WithAllTraceOptions(),
        ocsql.WithRowsClose(false),
        ocsql.WithRowsNext(false),
        ocsql.WithDisableErrSkip(true),
    )
}
// Open new connection and start stats recorder.
func Open(dsn string) *ent.Client {
    db := sql.OpenDB(connector{dsn})
    // Create an ent.Driver from `db`.
    drv := entsql.OpenDB("mysql", db)
    return ent.NewClient(ent.Driver(drv))
}

參考資料

https://entgo.io/docs/sql-integration/github

相關文章
相關標籤/搜索