You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
go-zero/core/service/servicegroup.go

118 lines
2.2 KiB
Go

4 years ago
package service
import (
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/proc"
"github.com/zeromicro/go-zero/core/syncx"
"github.com/zeromicro/go-zero/core/threading"
4 years ago
)
type (
// Starter is the interface wraps the Start method.
4 years ago
Starter interface {
Start()
}
// Stopper is the interface wraps the Stop method.
4 years ago
Stopper interface {
Stop()
}
// Service is the interface that groups Start and Stop methods.
4 years ago
Service interface {
Starter
Stopper
}
// A ServiceGroup is a group of services.
// Attention: the starting order of the added services is not guaranteed.
ServiceGroup struct {
4 years ago
services []Service
stopOnce func()
}
)
// NewServiceGroup returns a ServiceGroup.
func NewServiceGroup() *ServiceGroup {
sg := new(ServiceGroup)
4 years ago
sg.stopOnce = syncx.Once(sg.doStop)
return sg
}
// Add adds service into sg.
func (sg *ServiceGroup) Add(service Service) {
// push front, stop with reverse order.
sg.services = append([]Service{service}, sg.services...)
4 years ago
}
// Start starts the ServiceGroup.
4 years ago
// There should not be any logic code after calling this method, because this method is a blocking one.
// Also, quitting this method will close the logx output.
func (sg *ServiceGroup) Start() {
4 years ago
proc.AddShutdownListener(func() {
logx.Info("Shutting down services in group")
4 years ago
sg.stopOnce()
})
sg.doStart()
}
// Stop stops the ServiceGroup.
func (sg *ServiceGroup) Stop() {
4 years ago
sg.stopOnce()
}
func (sg *ServiceGroup) doStart() {
4 years ago
routineGroup := threading.NewRoutineGroup()
for i := range sg.services {
service := sg.services[i]
routineGroup.Run(func() {
4 years ago
service.Start()
})
}
routineGroup.Wait()
}
func (sg *ServiceGroup) doStop() {
4 years ago
for _, service := range sg.services {
service.Stop()
}
}
// WithStart wraps a start func as a Service.
4 years ago
func WithStart(start func()) Service {
return startOnlyService{
start: start,
}
}
// WithStarter wraps a Starter as a Service.
4 years ago
func WithStarter(start Starter) Service {
return starterOnlyService{
Starter: start,
}
}
type (
stopper struct{}
4 years ago
startOnlyService struct {
start func()
stopper
}
starterOnlyService struct {
Starter
stopper
}
)
func (s stopper) Stop() {
}
func (s startOnlyService) Start() {
s.start()
}