service.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package service
  2. import (
  3. "context"
  4. "sync"
  5. "go-common/app/admin/main/creative/conf"
  6. "go-common/app/admin/main/creative/dao"
  7. "go-common/library/log"
  8. "github.com/jinzhu/gorm"
  9. )
  10. // Service str
  11. type Service struct {
  12. conf *conf.Config
  13. dao *dao.Dao
  14. DB *gorm.DB
  15. DBArchive *gorm.DB
  16. wg sync.WaitGroup
  17. asynch chan func()
  18. closed bool
  19. }
  20. // New fn
  21. func New(c *conf.Config) (s *Service) {
  22. s = &Service{
  23. conf: c,
  24. dao: dao.New(c),
  25. asynch: make(chan func(), 10240),
  26. }
  27. s.DB = s.dao.DB
  28. s.DBArchive = s.dao.DBArchive
  29. s.wg.Add(1)
  30. go s.asynproc()
  31. return
  32. }
  33. // Ping fn
  34. func (s *Service) Ping(c context.Context) (err error) {
  35. return s.dao.Ping(c)
  36. }
  37. func (s *Service) addAsyn(f func()) {
  38. select {
  39. case s.asynch <- f:
  40. default:
  41. log.Warn("asynproc chan full")
  42. }
  43. }
  44. // cacheproc is a routine for executing closure.
  45. func (s *Service) asynproc() {
  46. defer s.wg.Done()
  47. for {
  48. if s.closed {
  49. return
  50. }
  51. f, ok := <-s.asynch
  52. if !ok {
  53. return
  54. }
  55. f()
  56. }
  57. }
  58. // Close dao
  59. func (s *Service) Close() {
  60. s.dao.Close()
  61. s.closed = true
  62. s.wg.Wait()
  63. }