mysqlpool.go 909 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package mysqlpool
  2. import (
  3. "errors"
  4. "strings"
  5. "sync"
  6. "golang-fave/engine/sqlw"
  7. )
  8. type MySqlPool struct {
  9. sync.RWMutex
  10. connections map[string]*sqlw.DB
  11. }
  12. func New() *MySqlPool {
  13. r := MySqlPool{}
  14. r.connections = map[string]*sqlw.DB{}
  15. return &r
  16. }
  17. func (this *MySqlPool) Get(key string) *sqlw.DB {
  18. // TODO: return nil if context canceled!
  19. this.Lock()
  20. defer this.Unlock()
  21. if value, ok := this.connections[key]; ok == true {
  22. return value
  23. }
  24. return nil
  25. }
  26. func (this *MySqlPool) Set(key string, value *sqlw.DB) {
  27. this.Lock()
  28. defer this.Unlock()
  29. this.connections[key] = value
  30. }
  31. func (this *MySqlPool) Close() error {
  32. this.Lock()
  33. defer this.Unlock()
  34. var errs []string
  35. for _, c := range this.connections {
  36. if c != nil {
  37. if err := c.Close(); err != nil {
  38. errs = append(errs, err.Error())
  39. }
  40. }
  41. }
  42. if len(errs) > 0 {
  43. return errors.New(strings.Join(errs, ", "))
  44. }
  45. return nil
  46. }