项目作者: rb-pkg

项目描述 :
Golang goroutine safe buffered slice - flush slice on size limit or time limit reach
高级语言: Go
项目地址: git://github.com/rb-pkg/buflice.git
创建时间: 2019-09-02T18:20:47Z
项目社区:https://github.com/rb-pkg/buflice

开源协议:MIT License

下载


buflice

This package need to create buffered slice that can be flushed when reach size or duration limit

When it can be needed?

Example: You have a worker for rabbitmq that receives jobs from queue. You receive them one by one and process it. But sometimes
you need to accumulate data from jobs for batch processing in database.

Website | Blog

license
GoDoc
Coverage Status
Build Status
Go Report Card

Installation

  1. go get -u github.com/rb-pkg/buflice

Example (dirty example)

  1. package main
  2. import (
  3. "log"
  4. "sync"
  5. "time"
  6. "github.com/rb-pkg/buflice"
  7. )
  8. type Book struct {
  9. Author string
  10. }
  11. func flushProcessor(chFlush chan []interface{}, chDone chan struct{}, wait *sync.WaitGroup) {
  12. for {
  13. select {
  14. case data := <-chFlush:
  15. wait.Add(1)
  16. log.Printf("%+v", data)
  17. wait.Done()
  18. case <-chDone:
  19. log.Println("Finished flushProcessor")
  20. return
  21. }
  22. }
  23. }
  24. func main() {
  25. chFlush := make(chan []interface{})
  26. chDone := make(chan struct{})
  27. wait := sync.WaitGroup{}
  28. bfl := buflice.NewBuflice(10, 1000*time.Millisecond, chFlush)
  29. go flushProcessor(chFlush, chDone, &wait)
  30. bfl.Start()
  31. bfl.Add(Book{Author: "Author #1"})
  32. bfl.Add(Book{Author: "Author #2"})
  33. bfl.Add(Book{Author: "Author #3"})
  34. bfl.Add(Book{Author: "Author #4"})
  35. bfl.Add(Book{Author: "Author #5"})
  36. time.Sleep(1111 * time.Millisecond)
  37. bfl.Add(Book{Author: "Author #6"})
  38. bfl.Add(Book{Author: "Author #7"})
  39. bfl.Add(Book{Author: "Author #8"})
  40. bfl.Add(Book{Author: "Author #9"})
  41. bfl.Add(Book{Author: "Author #10"})
  42. err := bfl.Close()
  43. if err != nil {
  44. log.Fatalln(err)
  45. }
  46. wait.Wait()
  47. chDone <- struct{}{}
  48. }

Will print:

  1. 2019/09/03 14:56:28 [Record #1 Record #2 Record #3 Record #4 Record #5 Record #6]
  2. 2019/09/03 14:56:28 [Record #7 Record #8 Record #9 Record #10]
  3. 2019/09/03 14:56:28 Finished flushProcessor

Credits

Thanks to: