另客网go项目公用的代码库

retry.go 713B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package linker
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. var (
  7. rt *ReTry
  8. once sync.Once
  9. )
  10. type ReTry struct {
  11. items sync.Map
  12. timeout time.Duration
  13. }
  14. type Item struct {
  15. Channel string
  16. Ctx Context
  17. Value interface{}
  18. }
  19. func NewRetry(timeout time.Duration) *ReTry {
  20. once.Do(func() {
  21. rt = &ReTry{items: sync.Map{}, timeout: timeout}
  22. })
  23. return rt
  24. }
  25. func (rt *ReTry) Put(key interface{}, value *Item) {
  26. rt.items.Store(key, value)
  27. go func(rt *ReTry) {
  28. <-time.NewTimer(rt.timeout).C
  29. if v, ok := rt.items.Load(key); ok {
  30. if i, ok := v.(*Item); ok {
  31. i.Ctx.Write(i.Channel, i.Value)
  32. rt.Delete(key)
  33. }
  34. }
  35. return
  36. }(rt)
  37. }
  38. func (rt *ReTry) Delete(key interface{}) {
  39. rt.items.Delete(key)
  40. }