service.go 1.4 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
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{
hujiebin's avatar
hujiebin committed
26 27 28 29
			Db:           mysql.Db,
			MyContext:    mycontext.CreateMyContext(nil),
			Redis:        redisCli.GetRedis(),
			RedisCluster: redisCli.GetClusterRedis(),
hujiebin's avatar
hujiebin committed
30 31 32
		}}
	} else {
		return &Service{CtxAndDb: &CtxAndDb{
hujiebin's avatar
hujiebin committed
33 34 35 36
			Db:           mysql.Db,
			MyContext:    myContext,
			Redis:        redisCli.GetRedis(),
			RedisCluster: redisCli.GetClusterRedis(),
hujiebin's avatar
hujiebin committed
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
		}}
	}
}

//事务钩子回调,遇到错误,异常则回调,写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
}