Block a user
xorm/session.go 里的 slice2Bean() 方法能加点注释么,很多代码看不懂要做什么
能不能在 session.LastSQL() 里多返回一个该 SQL 的执行时间呢?用于上报统计
能不能在 session.LastSQL() 里多返回一个该 SQL 的执行时间呢?用于上报统计
You could use
ContextHook
to do that.这个
ContextHook
有使用文档么?ReadMe 里没有找到这方面的内容
这样实现倒是可用, 相关部分代码下 :
// 一个DB代表一个可以操作具体数据库的连接池
type DB struct {
engine *xorm.Engine
session *xorm.Session // 到具体数据库的操作会话
lastSQL string // 最后一条SQL
lastSQLTime time.Duration // 执行时间
num int // 获取的条数
startidx int // 起始的 index
// ...
}
// 执行时间的钩子对象
type ExecTimeHook struct {
before func(c *contexts.ContextHook) (context.Context, error)
after func(c *contexts.ContextHook) error
}
func (h *ExecTimeHook) BeforeProcess(c *contexts.ContextHook) (context.Context, error) {
return h.before(c)
}
func (h *ExecTimeHook) AfterProcess(c *contexts.ContextHook) error {
return h.after(c)
}
func doNothingBeforeHook(c *contexts.ContextHook) (context.Context, error) {
return c.Ctx, nil
}
// 执行一条 Select 查询语句
func (db *DB) Query(sql string) (Rows, error) {
// 这里将钩子函数注册进去,拿到 SQL 和 执行时间后,给回到 DB 对象的属性上
db.engine.AddHook(&ExecTimeHook{
before: doNothingBeforeHook,
after: func(c *contexts.ContextHook) error {
db.lastSQLTime = c.ExecuteTime
db.lastSQL, _ = builder.ConvertToBoundSQL(c.SQL, c.Args)
return nil
},
})
ret, err := db.session.QueryInterface(sql)
if err != nil {
return nil, err
}
// ...
}
// 获取最后执行的一条SQL
func (db *DB) GetLastSQL() string {
defer func() {
db.lastSQL = ""
}()
return db.lastSQL
}
// 获取最后执行的一条SQL 执行时间
func (db *DB) GetLastSQLTime() time.Duration {
defer func() {
db.lastSQLTime = 0
}()
return db.lastSQLTime
}
能不能在 session.LastSQL() 里多返回一个该 SQL 的执行时间呢?用于上报统计
You could use
ContextHook
to do that.
这个ContextHook
有使用文档么?
ReadMe 里没有找到这方面的内容
能不能在 session.LastSQL() 里多返回一个该 SQL 的执行时间呢?用于上报统计
[xorm] [info] 2020/08/17 16:36:22.299588 [SQL] INSERT INTO `user` (`age`,`created`,`name`,`passwd`,`salt`,`updated`) VALUES (?,?,?,?,?,?) [81 2020-08-17 16:36:22.251513637 +0800 CST m=+0.001122265 link justfortest sdfwefsff 2020-08-17 16:36:22.251513472 +0800 CST m=+0.001122103] - 34.018748ms
开启日志后,可以看到 SQL 的执行时间是有记录的,那么有没有简单的方法,可以将 这个 执行时间,在业务代码里面获取呢?而不是记录到日志里?
能不能在 session.LastSQL() 里多返回一个该 SQL 的执行时间呢?用于上报统计
获取最后执行的那条 SQL 语句 ?
sess := engine.NewSession() defer sess.Close() sess.Exec(...) sess.LastSQL()
got it ! 多谢!
这个库内部是已经有重连机制么,不需要业务方再额外开 GoRoutine 去保持连接状态?
Xorm 业务是 Daemon Service ,我关闭 MySQL Server 后,可以看到操作失败的记录,然后重启MySQL Server 后,Xorm 的操作也就恢复了。