mysql_store.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package mysql
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/filer"
  6. "time"
  7. "github.com/chrislusf/seaweedfs/weed/filer/abstract_sql"
  8. "github.com/chrislusf/seaweedfs/weed/util"
  9. _ "github.com/go-sql-driver/mysql"
  10. )
  11. const (
  12. CONNECTION_URL_PATTERN = "%s:%s@tcp(%s:%d)/%s?charset=utf8"
  13. )
  14. func init() {
  15. filer.Stores = append(filer.Stores, &MysqlStore{})
  16. }
  17. type MysqlStore struct {
  18. abstract_sql.AbstractSqlStore
  19. }
  20. func (store *MysqlStore) GetName() string {
  21. return "mysql"
  22. }
  23. func (store *MysqlStore) Initialize(configuration util.Configuration, prefix string) (err error) {
  24. return store.initialize(
  25. configuration.GetString(prefix+"username"),
  26. configuration.GetString(prefix+"password"),
  27. configuration.GetString(prefix+"hostname"),
  28. configuration.GetInt(prefix+"port"),
  29. configuration.GetString(prefix+"database"),
  30. configuration.GetInt(prefix+"connection_max_idle"),
  31. configuration.GetInt(prefix+"connection_max_open"),
  32. configuration.GetInt(prefix+"connection_max_lifetime_seconds"),
  33. configuration.GetBool(prefix+"interpolateParams"),
  34. )
  35. }
  36. func (store *MysqlStore) initialize(user, password, hostname string, port int, database string, maxIdle, maxOpen,
  37. maxLifetimeSeconds int, interpolateParams bool) (err error) {
  38. store.SupportBucketTable = false
  39. store.SqlGenerator = &SqlGenMysql{
  40. CreateTableSqlTemplate: "",
  41. DropTableSqlTemplate: "drop table %s",
  42. }
  43. sqlUrl := fmt.Sprintf(CONNECTION_URL_PATTERN, user, password, hostname, port, database)
  44. if interpolateParams {
  45. sqlUrl += "&interpolateParams=true"
  46. }
  47. var dbErr error
  48. store.DB, dbErr = sql.Open("mysql", sqlUrl)
  49. if dbErr != nil {
  50. store.DB.Close()
  51. store.DB = nil
  52. return fmt.Errorf("can not connect to %s error:%v", sqlUrl, err)
  53. }
  54. store.DB.SetMaxIdleConns(maxIdle)
  55. store.DB.SetMaxOpenConns(maxOpen)
  56. store.DB.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
  57. if err = store.DB.Ping(); err != nil {
  58. return fmt.Errorf("connect to %s error:%v", sqlUrl, err)
  59. }
  60. return nil
  61. }