go-zero处理本地事务,
sqlx.SqlConn 提供了基础的事务机制,官方代码
go
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
}
})
改造的代码
1.在生成的model文件userauthmodel.go中添加代码
go
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)
})
}
2.在逻辑层处理代码
go
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