Browse Source

MySQL connection optimization

Vova Tkach 5 years ago
parent
commit
2c2e3b7916
2 changed files with 18 additions and 11 deletions
  1. 6 0
      engine/mysqlpool/mysqlpool.go
  2. 12 11
      engine/wrapper/wrapper.go

+ 6 - 0
engine/mysqlpool/mysqlpool.go

@@ -35,6 +35,12 @@ func (this *MySqlPool) Set(key string, value *sqlw.DB) {
 	this.connections[key] = value
 }
 
+func (this *MySqlPool) Del(key string) {
+	if _, ok := this.connections[key]; ok {
+		delete(this.connections, key)
+	}
+}
+
 func (this *MySqlPool) Close() error {
 	this.Lock()
 	defer this.Unlock()

+ 12 - 11
engine/wrapper/wrapper.go

@@ -116,6 +116,12 @@ func (this *Wrapper) dbReconnect() error {
 	if err != nil {
 		return err
 	}
+
+	// Max 60 minutes and max 8 connection per host
+	this.DB.SetConnMaxLifetime(time.Minute * 60)
+	this.DB.SetMaxIdleConns(8)
+	this.DB.SetMaxOpenConns(8)
+
 	this.MSPool.Set(this.CurrHost, this.DB)
 	return nil
 }
@@ -127,23 +133,18 @@ func (this *Wrapper) UseDatabase() error {
 			return err
 		}
 	}
-
 	if err := this.DB.Ping(this.R.Context()); err != nil {
 		this.DB.Close()
 		if err := this.dbReconnect(); err != nil {
 			return err
-		}
-		if err := this.DB.Ping(this.R.Context()); err != nil {
-			this.DB.Close()
-			return err
+		} else {
+			if err := this.DB.Ping(this.R.Context()); err != nil {
+				this.DB.Close()
+				this.MSPool.Del(this.CurrHost)
+				return err
+			}
 		}
 	}
-
-	// Max 60 minutes and max 4 connection per host
-	this.DB.SetConnMaxLifetime(time.Minute * 60)
-	this.DB.SetMaxIdleConns(8)
-	this.DB.SetMaxOpenConns(8)
-
 	return nil
 }