cleaned
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"authorization/helper"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"log"
|
||||
@@ -14,9 +13,6 @@ import (
|
||||
// DB is the global database connection pool
|
||||
var DB *sql.DB
|
||||
|
||||
// DBCircuitBreaker protects database operations
|
||||
var DBCircuitBreaker *helper.CircuitBreaker
|
||||
|
||||
func InitDB() (*sql.DB, error) {
|
||||
// Get connection details from environment variables (loaded in main)
|
||||
connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?parseTime=true",
|
||||
@@ -33,19 +29,14 @@ func InitDB() (*sql.DB, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error opening database: %v", err)
|
||||
}
|
||||
// Initialize circuit breaker
|
||||
DBCircuitBreaker = helper.NewCircuitBreaker("database", 5, 2*time.Second)
|
||||
|
||||
// Set connection pool parameters optimized for horizontal scaling
|
||||
// Lower per-replica to allow more replicas without exhausting DB connections
|
||||
DB.SetMaxOpenConns(25) // Maximum number of open connections to the database
|
||||
DB.SetMaxIdleConns(10) // Maximum number of connections in the idle connection pool
|
||||
DB.SetConnMaxLifetime(5 * time.Minute) // Maximum amount of time a connection may be reused
|
||||
|
||||
// Check if the database connection is working with circuit breaker
|
||||
err = DBCircuitBreaker.Call(func() error {
|
||||
return DB.Ping()
|
||||
})
|
||||
// Check if the database connection is working
|
||||
err = DB.Ping()
|
||||
if err != nil {
|
||||
log.Printf("Database connection lost: %v. Reconnecting...", err)
|
||||
DB, err = InitDB()
|
||||
|
||||
Reference in New Issue
Block a user