From cf7252314a2a74143ccb7afc3864907b08ecefd6 Mon Sep 17 00:00:00 2001 From: hujiebin Date: Wed, 8 Feb 2023 16:30:09 +0800 Subject: [PATCH] =?UTF-8?q?domain=E4=B9=9Fok=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- domain/ctx.go | 13 ++++++++++++ domain/event.go | 9 ++++++++ domain/model.go | 55 +++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+) create mode 100644 domain/ctx.go create mode 100644 domain/event.go create mode 100644 domain/model.go diff --git a/domain/ctx.go b/domain/ctx.go new file mode 100644 index 0000000..d433cca --- /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 0000000..97af5d7 --- /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 0000000..42a43c9 --- /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 +} -- 2.22.0