From 8d8ceb620297f81f52d591d51e1068c1daac44c3 Mon Sep 17 00:00:00 2001 From: hujiebin Date: Fri, 24 Feb 2023 12:09:54 +0800 Subject: [PATCH] Create service.go --- domain/service.go | 58 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 domain/service.go diff --git a/domain/service.go b/domain/service.go new file mode 100644 index 0000000..70bc4a2 --- /dev/null +++ b/domain/service.go @@ -0,0 +1,58 @@ +package domain + +import ( + "git.hilo.cn/hilo-common/mycontext" + "git.hilo.cn/hilo-common/resource/mysql" + "git.hilo.cn/hilo-common/resource/redisCli" + "runtime/debug" +) + +type Service struct { + *CtxAndDb +} + +func (service *Service) getMyContext() *mycontext.MyContext { + return service.MyContext +} + +/** + * 创建服务 + * @param + * @return + **/ +func CreateService(myContext *mycontext.MyContext) *Service { + if myContext == nil { + return &Service{CtxAndDb: &CtxAndDb{ + Db: mysql.Db, + MyContext: mycontext.CreateMyContext(nil), + Redis: redisCli.GetRedis(), + }} + } else { + return &Service{CtxAndDb: &CtxAndDb{ + Db: mysql.Db, + MyContext: myContext, + Redis: redisCli.GetRedis(), + }} + } +} + +//事务钩子回调,遇到错误,异常则回调,写service都需要钩子回调 +func (service *Service) Transactional(callback func() error) error { + //异常回调 + defer func() { + if err := recover(); err != nil { + service.Log.Errorf("doTransactional SYSTEM ACTION PANIC: %v, stack: %v", err, string(debug.Stack())) + service.Db.Rollback() + //为了防止给controller层造成数据错误,继续抛恐慌 + panic(err) + } + }() + service.CtxAndDb.Db = mysql.Db.Begin() + err := callback() + if err != nil { + service.Db.Rollback() + return err + } + //提交 + return service.Db.Commit().Error +} -- 2.22.0