github.com/zly-app/zapp@v1.3.3/service.go (about)

     1  /*
     2  -------------------------------------------------
     3     Author :       zlyuancn
     4     date:         2021/1/20
     5     Description :
     6  -------------------------------------------------
     7  */
     8  
     9  package zapp
    10  
    11  import (
    12  	"go.uber.org/zap"
    13  
    14  	"github.com/zly-app/zapp/core"
    15  	"github.com/zly-app/zapp/logger"
    16  	"github.com/zly-app/zapp/service"
    17  )
    18  
    19  // 构建服务
    20  func (app *appCli) makeService() {
    21  	err := app.opt.CheckServices(app)
    22  	if err != nil {
    23  		app.Fatal("服务检查失败", zap.Error(err))
    24  	}
    25  
    26  	for _, serviceType := range app.opt.Services {
    27  		app.services[serviceType] = service.MakeService(app, serviceType)
    28  	}
    29  }
    30  
    31  func (app *appCli) startService() {
    32  	app.Debug("启动服务")
    33  	for _, serviceType := range app.opt.Services {
    34  		s, ok := app.services[serviceType]
    35  		if !ok {
    36  			app.Fatal("服务查找失败", zap.String("serviceType", string(serviceType)))
    37  		}
    38  
    39  		err := service.WaitRun(app, &service.WaitRunOption{
    40  			ServiceType:        serviceType,
    41  			ExitOnErrOfObserve: app.opt.ExitOnErrOfObserveServiceUnstable,
    42  			RunServiceFn:       s.Start,
    43  		})
    44  		if err != nil {
    45  			app.Fatal("服务启动失败", zap.String("serviceType", string(serviceType)), zap.Error(err))
    46  		}
    47  	}
    48  }
    49  
    50  func (app *appCli) closeService() {
    51  	app.Debug("关闭服务")
    52  	for _, serviceType := range app.opt.Services {
    53  		s, ok := app.services[serviceType]
    54  		if !ok {
    55  			app.Fatal("服务查找失败", zap.String("serviceType", string(serviceType)))
    56  		}
    57  
    58  		if err := s.Close(); err != nil {
    59  			app.Error("服务关闭失败", zap.String("serviceType", string(serviceType)), zap.Error(err))
    60  		}
    61  	}
    62  }
    63  
    64  func (app *appCli) GetService(serviceType core.ServiceType) (core.IService, bool) {
    65  	s, ok := app.services[serviceType]
    66  	return s, ok
    67  }
    68  
    69  func (app *appCli) InjectService(serviceType core.ServiceType, a ...interface{}) {
    70  	s, ok := app.GetService(serviceType)
    71  	if !ok {
    72  		if app.opt.IgnoreInjectOfDisableService {
    73  			return
    74  		}
    75  		logger.Log.Fatal("注入失败, 未启用服务", zap.String("serviceType", string(serviceType)))
    76  	}
    77  
    78  	s.Inject(a...)
    79  }