servicegroup.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package service
  2. import (
  3. "log"
  4. "git.i2edu.net/i2/go-zero/core/proc"
  5. "git.i2edu.net/i2/go-zero/core/syncx"
  6. "git.i2edu.net/i2/go-zero/core/threading"
  7. )
  8. type (
  9. // Starter is the interface wraps the Start method.
  10. Starter interface {
  11. Start()
  12. }
  13. // Stopper is the interface wraps the Stop method.
  14. Stopper interface {
  15. Stop()
  16. }
  17. // Service is the interface that groups Start and Stop methods.
  18. Service interface {
  19. Starter
  20. Stopper
  21. }
  22. // A ServiceGroup is a group of services.
  23. ServiceGroup struct {
  24. services []Service
  25. stopOnce func()
  26. }
  27. )
  28. // NewServiceGroup returns a ServiceGroup.
  29. func NewServiceGroup() *ServiceGroup {
  30. sg := new(ServiceGroup)
  31. sg.stopOnce = syncx.Once(sg.doStop)
  32. return sg
  33. }
  34. // Add adds service into sg.
  35. func (sg *ServiceGroup) Add(service Service) {
  36. sg.services = append(sg.services, service)
  37. }
  38. // Start starts the ServiceGroup.
  39. // There should not be any logic code after calling this method, because this method is a blocking one.
  40. // Also, quitting this method will close the logx output.
  41. func (sg *ServiceGroup) Start() {
  42. proc.AddShutdownListener(func() {
  43. log.Println("Shutting down...")
  44. sg.stopOnce()
  45. })
  46. sg.doStart()
  47. }
  48. // Stop stops the ServiceGroup.
  49. func (sg *ServiceGroup) Stop() {
  50. sg.stopOnce()
  51. }
  52. func (sg *ServiceGroup) doStart() {
  53. routineGroup := threading.NewRoutineGroup()
  54. for i := range sg.services {
  55. service := sg.services[i]
  56. routineGroup.RunSafe(func() {
  57. service.Start()
  58. })
  59. }
  60. routineGroup.Wait()
  61. }
  62. func (sg *ServiceGroup) doStop() {
  63. for _, service := range sg.services {
  64. service.Stop()
  65. }
  66. }
  67. // WithStart wraps a start func as a Service.
  68. func WithStart(start func()) Service {
  69. return startOnlyService{
  70. start: start,
  71. }
  72. }
  73. // WithStarter wraps a Starter as a Service.
  74. func WithStarter(start Starter) Service {
  75. return starterOnlyService{
  76. Starter: start,
  77. }
  78. }
  79. type (
  80. stopper struct{}
  81. startOnlyService struct {
  82. start func()
  83. stopper
  84. }
  85. starterOnlyService struct {
  86. Starter
  87. stopper
  88. }
  89. )
  90. func (s stopper) Stop() {
  91. }
  92. func (s startOnlyService) Start() {
  93. s.start()
  94. }