mysqlpool.go 987 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. this.Lock()
  19. defer this.Unlock()
  20. if value, ok := this.connections[key]; ok == true {
  21. return value
  22. }
  23. return nil
  24. }
  25. func (this *MySqlPool) Set(key string, value *sqlw.DB) {
  26. this.Lock()
  27. defer this.Unlock()
  28. this.connections[key] = value
  29. }
  30. func (this *MySqlPool) Del(key string) {
  31. if _, ok := this.connections[key]; ok {
  32. delete(this.connections, key)
  33. }
  34. }
  35. func (this *MySqlPool) Close() error {
  36. this.Lock()
  37. defer this.Unlock()
  38. var errs []string
  39. for _, c := range this.connections {
  40. if c != nil {
  41. if err := c.Close(); err != nil {
  42. errs = append(errs, err.Error())
  43. }
  44. }
  45. }
  46. if len(errs) > 0 {
  47. return errors.New(strings.Join(errs, ", "))
  48. }
  49. return nil
  50. }