cache.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package cache
  2. import (
  3. "errors"
  4. "runtime"
  5. "sync"
  6. "go-common/library/log"
  7. "go-common/library/stat/prom"
  8. )
  9. var (
  10. // ErrFull cache internal chan full.
  11. ErrFull = errors.New("cache chan full")
  12. stats = prom.BusinessInfoCount
  13. )
  14. // Cache async save data by chan.
  15. type Cache struct {
  16. ch chan func()
  17. worker int
  18. waiter sync.WaitGroup
  19. }
  20. // Deprecated: use library/sync/pipeline/fanout instead.
  21. func New(worker, size int) *Cache {
  22. if worker <= 0 {
  23. worker = 1
  24. }
  25. c := &Cache{
  26. ch: make(chan func(), size),
  27. worker: worker,
  28. }
  29. c.waiter.Add(worker)
  30. for i := 0; i < worker; i++ {
  31. go c.proc()
  32. }
  33. return c
  34. }
  35. func (c *Cache) proc() {
  36. defer c.waiter.Done()
  37. for {
  38. f := <-c.ch
  39. if f == nil {
  40. return
  41. }
  42. wrapFunc(f)()
  43. stats.State("cache_channel", int64(len(c.ch)))
  44. }
  45. }
  46. func wrapFunc(f func()) (res func()) {
  47. res = func() {
  48. defer func() {
  49. if r := recover(); r != nil {
  50. buf := make([]byte, 64*1024)
  51. buf = buf[:runtime.Stack(buf, false)]
  52. log.Error("panic in cache proc, err: %s, stack: %s", r, buf)
  53. }
  54. }()
  55. f()
  56. }
  57. return
  58. }
  59. // Save save a callback cache func.
  60. func (c *Cache) Save(f func()) (err error) {
  61. if f == nil {
  62. return
  63. }
  64. select {
  65. case c.ch <- f:
  66. default:
  67. err = ErrFull
  68. }
  69. stats.State("cache_channel", int64(len(c.ch)))
  70. return
  71. }
  72. // Close close cache
  73. func (c *Cache) Close() (err error) {
  74. for i := 0; i < c.worker; i++ {
  75. c.ch <- nil
  76. }
  77. c.waiter.Wait()
  78. return
  79. }