You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

59 lines
1.4 KiB

  1. package mysql
  2. import (
  3. "fmt"
  4. "database/sql"
  5. "github.com/chrislusf/seaweedfs/weed/filer2"
  6. "github.com/spf13/viper"
  7. _ "github.com/go-sql-driver/mysql"
  8. "github.com/chrislusf/seaweedfs/weed/filer2/abstract_sql"
  9. )
  10. const (
  11. CONNECTION_URL_PATTERN = "%s:%s@tcp(%s:%d)/%s?charset=utf8"
  12. )
  13. func init() {
  14. filer2.Stores = append(filer2.Stores, &MysqlStore{})
  15. }
  16. type MysqlStore struct {
  17. abstract_sql.AbstractSqlStore
  18. }
  19. func (store *MysqlStore) GetName() string {
  20. return "mysql"
  21. }
  22. func (store *MysqlStore) Initialize(viper *viper.Viper) (err error) {
  23. return store.initialize(
  24. viper.GetString("username"),
  25. viper.GetString("password"),
  26. viper.GetString("hostname"),
  27. viper.GetInt("port"),
  28. viper.GetString("database"),
  29. viper.GetInt("connection_max_idle"),
  30. viper.GetInt("connection_max_open"),
  31. )
  32. }
  33. func (store *MysqlStore) initialize(user, password, hostname string, port int, database string, maxIdle, maxOpen int) (err error) {
  34. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  35. var dbErr error
  36. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  37. if dbErr != nil {
  38. store.DB.Close()
  39. store.DB = nil
  40. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  41. }
  42. store.DB.SetMaxIdleConns(maxIdle)
  43. store.DB.SetMaxOpenConns(maxOpen)
  44. if err = store.DB.Ping(); err != nil {
  45. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  46. }
  47. return nil
  48. }