赞
踩
go-zero处理本地事务,
sqlx.SqlConn 提供了基础的事务机制,官方代码
var conn sqlx.SqlConn
err := conn.TransactCtx(context.Background(), func(ctx context.Context, session sqlx.Session) error {
r, err := session.ExecCtx(ctx, "insert into user (id, name) values (?, ?)", 1, "test")
if err != nil {
return err
}
r ,err =session.ExecCtx(ctx, "insert into user (id, name) values (?, ?)", 2, "test")
if err != nil {
return err
}
})
改造的代码
package user import ( "context" "github.com/zeromicro/go-zero/core/stores/sqlx" ) var _ UserAuthModel = (*customUserAuthModel)(nil) type ( UserAuthModel interface { UserAuthModel withSession(session sqlx.Session) UserAuthModel // 添加代码1 TransactCtx(ctx context.Context, fn func(context context.Context, session sqlx.Session) error) error } customUserAuthModel struct { *defaultUserAuthModel } ) func NewUserAuthModel(conn sqlx.SqlConn) UserAuthModel { return &customUserAuthModel{ defaultUserAuthModel: newUserAuthModel(conn), } } func (m *customUserAuthModel) withSession(session sqlx.Session) UserAuthModel { return NewUserAuthModel(sqlx.NewSqlConnFromSession(session)) } // 添加代码2 func (m *customUserAuthModel) TransactCtx(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error { return m.conn.TransactCtx(ctx, func(ctx context.Context, session sqlx.Session) error { return fn(ctx, session) }) }
err := l.UserAuthModel.TransactCtx(context.Background(), func(ctx context.Context, session sqlx.Session) error { t := time.Now() // 在这里执行数据库操作 _, err := session.Exec(`INSERT INTO _user_auth ( user_id,updated_time,created_time) VALUES (?, ?, ? )`, 11111, t, t) if err != nil { return err } _, err = session.Exec(`INSERT INTO _user_auth_log ( user_id,updated_time,created_time) VALUES (?, ?, ? )`, 11111, t, t) if err != nil { return err } if err != nil { return err } return nil }) if err != nil { logx.ErrorStack("Transaction failed:", err) } return err
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。