diff --git a/domain/ctx.go b/domain/ctx.go new file mode 100644 index 0000000000000000000000000000000000000000..d433ccaf8849a4460992dbc9eed43768701666f0 --- /dev/null +++ b/domain/ctx.go @@ -0,0 +1,13 @@ +package domain + +import ( + "git.hilo.cn/hilo-common/mycontext" + "github.com/go-redis/redis/v8" + "gorm.io/gorm" +) + +type CtxAndDb struct { + Db *gorm.DB + *mycontext.MyContext + Redis *redis.Client +} diff --git a/domain/event.go b/domain/event.go new file mode 100644 index 0000000000000000000000000000000000000000..97af5d7285e0f1dcdb2024c65e24b11adeed463c --- /dev/null +++ b/domain/event.go @@ -0,0 +1,9 @@ +package domain + +//异步执行的接口 +type AsyncEvent interface { + AsyncDo(model *Model, eventData interface{}, n int) error + AsyncSize() int + AsyncNoTxDo(model *Model, eventData interface{}, n int) error + AsyncNoTxSize() int +} diff --git a/domain/model.go b/domain/model.go new file mode 100644 index 0000000000000000000000000000000000000000..42a43c97e8a8924a47d4a4d9a8d1e802b967dd74 --- /dev/null +++ b/domain/model.go @@ -0,0 +1,55 @@ +package domain + +import ( + "git.hilo.cn/hilo-common/mycontext" + "git.hilo.cn/hilo-common/resource/mysql" + "git.hilo.cn/hilo-common/resource/redisCli" + "gorm.io/gorm" +) + +type Model struct { + *CtxAndDb `gorm:"-"` +} + +func CreateModel(ctxAndDb *CtxAndDb) *Model { + return &Model{CtxAndDb: ctxAndDb} +} + +func CreateModelContext(myContext *mycontext.MyContext) *Model { + return &Model{ + CtxAndDb: &CtxAndDb{ + Db: mysql.Db, + MyContext: myContext, + Redis: redisCli.GetRedis(), + }, + } +} + +func CreateModelNil() *Model { + return &Model{ + CtxAndDb: &CtxAndDb{ + Db: mysql.Db, + MyContext: mycontext.CreateMyContext(nil), + Redis: redisCli.GetRedis(), + }, + } +} + +func (m *Model) DB() *gorm.DB { + return m.Db.WithContext(m) +} + +// 包装事务 +// 注意:需要使用新的model +func (m *Model) Transaction(f func(*Model) error) error { + // 公用context + // 新的db + txModel := CreateModelContext(m.MyContext) + txModel.Db = m.Db.Begin().WithContext(m) + err := f(txModel) + if err != nil { + txModel.Db.Rollback() + return err + } + return txModel.Db.Commit().Error +}