From aa4376074a1b9933a75640d9d52e3d67cc0212c7 Mon Sep 17 00:00:00 2001 From: Nikitin Aleksandr Date: Wed, 14 May 2025 16:10:09 +0300 Subject: [PATCH] =?UTF-8?q?=D1=81=D0=B4=D0=B5=D0=BB=D0=B0=D0=BB=20tinkoff?= =?UTF-8?q?=5Fconnect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- postgres_gorm/postgres_gorm.go | 13 ++++++--- postgres_pgx/postgres_pgx.go | 21 +++++++++------ .../postgres_sqlx.go | 10 +++---- .../postgres_sqlx_test.go | 2 +- postgres_stek/postgres_stek.go | 27 ++++++++++++------- tinkoff_connect/tinkoff_connect.go | 1 + 6 files changed, 47 insertions(+), 27 deletions(-) rename postgres_connect/postgres_connect.go => postgres_sqlx/postgres_sqlx.go (97%) rename postgres_connect/postgres_connect_test.go => postgres_sqlx/postgres_sqlx_test.go (98%) diff --git a/postgres_gorm/postgres_gorm.go b/postgres_gorm/postgres_gorm.go index e8fcd2a0..64aecf4f 100644 --- a/postgres_gorm/postgres_gorm.go +++ b/postgres_gorm/postgres_gorm.go @@ -30,8 +30,8 @@ var Conn *gorm.DB // log - глобальный логгер //var log = logger.GetLog() -// mutexReconnect - защита от многопоточности Reconnect() -var mutexReconnect = &sync.Mutex{} +// mutex_Connect - защита от многопоточности Connect() +var mutex_Connect = &sync.RWMutex{} // NeedReconnect - флаг необходимости переподключения var NeedReconnect bool @@ -170,8 +170,8 @@ func IsClosed() bool { // Reconnect повторное подключение к базе данных, если оно отключено // или полная остановка программы func Reconnect(err error) { - mutexReconnect.Lock() - defer mutexReconnect.Unlock() + mutex_Connect.Lock() + defer mutex_Connect.Unlock() if err == nil { return @@ -414,6 +414,11 @@ func GetDSN(ApplicationName string) string { // GetConnection - возвращает соединение к нужной базе данных func GetConnection() *gorm.DB { + //мьютекс чтоб не подключаться одновременно + mutex_Connect.RLock() + defer mutex_Connect.RUnlock() + + // if Conn == nil { err := Connect_err() if err != nil { diff --git a/postgres_pgx/postgres_pgx.go b/postgres_pgx/postgres_pgx.go index 29afdf50..8cde93da 100644 --- a/postgres_pgx/postgres_pgx.go +++ b/postgres_pgx/postgres_pgx.go @@ -31,8 +31,8 @@ import ( // Conn - соединение к базе данных var Conn *pgx.Conn -// mutexReconnect - защита от многопоточности Reconnect() -var mutexReconnect = &sync.RWMutex{} +// mutex_Connect - защита от многопоточности Connect() +var mutex_Connect = &sync.RWMutex{} // Settings хранит все нужные переменные окружения var Settings SettingsINI @@ -162,8 +162,8 @@ func IsClosed() bool { // Reconnect повторное подключение к базе данных, если оно отключено // или полная остановка программы func Reconnect(err error) { - mutexReconnect.Lock() - defer mutexReconnect.Unlock() + mutex_Connect.Lock() + defer mutex_Connect.Unlock() if err == nil { return @@ -234,8 +234,8 @@ func CloseConnection_err() error { ctx, cancel := context.WithTimeout(ctxMain, 60*time.Second) defer cancel() - mutexReconnect.Lock() - defer mutexReconnect.Unlock() + mutex_Connect.Lock() + defer mutex_Connect.Unlock() err := GetConnection().Close(ctx) @@ -376,10 +376,10 @@ loop: case <-ticker.C: //ping в базе данных - mutexReconnect.RLock() //race + mutex_Connect.RLock() //race //err = GetConnection().Ping(ctx) //ping делать нельзя т.к. data race err = Ping_err(ctx) - mutexReconnect.RUnlock() + mutex_Connect.RUnlock() if err != nil { switch err.Error() { case TextConnBusy: @@ -423,6 +423,11 @@ loop: // GetConnection - возвращает соединение к нужной базе данных func GetConnection() *pgx.Conn { + //мьютекс чтоб не подключаться одновременно + mutex_Connect.RLock() + defer mutex_Connect.RUnlock() + + // if Conn == nil || Conn.IsClosed() { err := Connect_err() if err != nil { diff --git a/postgres_connect/postgres_connect.go b/postgres_sqlx/postgres_sqlx.go similarity index 97% rename from postgres_connect/postgres_connect.go rename to postgres_sqlx/postgres_sqlx.go index 4f2ab311..cda58d1e 100644 --- a/postgres_connect/postgres_connect.go +++ b/postgres_sqlx/postgres_sqlx.go @@ -1,6 +1,6 @@ // модуль для работы с базой данных -package postgres_connect +package postgres_sqlx import ( "context" @@ -24,8 +24,8 @@ var Conn *sqlx.DB // log - глобальный логгер //var log = logger.GetLog() -// mutexReconnect - защита от многопоточности Reconnect() -var mutexReconnect = &sync.Mutex{} +// mutex_Connect - защита от многопоточности Reconnect() +var mutex_Connect = &sync.RWMutex{} // Settings хранит все нужные переменные окружения var Settings SettingsINI @@ -115,8 +115,8 @@ func IsClosed() bool { // Reconnect повторное подключение к базе данных, если оно отключено // или полная остановка программы func Reconnect(err error) { - mutexReconnect.Lock() - defer mutexReconnect.Unlock() + mutex_Connect.Lock() + defer mutex_Connect.Unlock() if err == nil { return diff --git a/postgres_connect/postgres_connect_test.go b/postgres_sqlx/postgres_sqlx_test.go similarity index 98% rename from postgres_connect/postgres_connect_test.go rename to postgres_sqlx/postgres_sqlx_test.go index 2095c4ad..aff53d87 100644 --- a/postgres_connect/postgres_connect_test.go +++ b/postgres_sqlx/postgres_sqlx_test.go @@ -1,4 +1,4 @@ -package postgres_connect +package postgres_sqlx import ( "errors" diff --git a/postgres_stek/postgres_stek.go b/postgres_stek/postgres_stek.go index 084c7a5b..53ec5116 100644 --- a/postgres_stek/postgres_stek.go +++ b/postgres_stek/postgres_stek.go @@ -39,13 +39,13 @@ var MapConnection = make(map[int64]connections.Connection) // log - глобальный логгер //var log = logger.GetLog() -// mutexReconnect - защита от многопоточности Reconnect() -var mutexReconnect = &sync.Mutex{} +// mutex_Connect - защита от многопоточности Reconnect() +var mutex_Connect = &sync.RWMutex{} // NeedReconnect - флаг необходимости переподключения var NeedReconnect bool -var MutexConnection sync.Mutex +//var MutexConnection sync.Mutex // Connect_err - подключается к базе данных func Connect(Connection connections.Connection) { @@ -107,12 +107,12 @@ func Connect_err(Connection connections.Connection) error { err = DB.Ping() } - MutexConnection.Lock() //race + mutex_Connect.Lock() //race MapConnection[Connection.ID] = Connection MapConn[Connection.ID] = Conn - MutexConnection.Unlock() + mutex_Connect.Unlock() return err } @@ -142,8 +142,8 @@ func IsClosed(Connection connections.Connection) bool { // Reconnect повторное подключение к базе данных, если оно отключено // или полная остановка программы func Reconnect(Connection connections.Connection, err error) { - mutexReconnect.Lock() - defer mutexReconnect.Unlock() + mutex_Connect.Lock() + defer mutex_Connect.Unlock() if err == nil { return @@ -248,12 +248,12 @@ func CloseConnection_err(Connection connections.Connection) error { } Conn = nil - MutexConnection.Lock() //race + mutex_Connect.Lock() //race delete(MapConnection, Connection.ID) delete(MapConn, Connection.ID) - MutexConnection.Unlock() + mutex_Connect.Unlock() return err } @@ -335,6 +335,15 @@ func GetDSN(Connection connections.Connection) string { // GetConnection - возвращает соединение к нужной базе данных func GetConnection(Connection connections.Connection) *gorm.DB { + //мьютекс чтоб не подключаться одновременно + mutex_Connect.RLock() + defer mutex_Connect.RUnlock() + + //мьютекс чтоб не подключаться одновременно + mutex_Connect.RLock() + defer mutex_Connect.RUnlock() + + // Conn := MapConn[Connection.ID] if Conn == nil { Connect(Connection) diff --git a/tinkoff_connect/tinkoff_connect.go b/tinkoff_connect/tinkoff_connect.go index 9081e727..fe5341f4 100644 --- a/tinkoff_connect/tinkoff_connect.go +++ b/tinkoff_connect/tinkoff_connect.go @@ -42,6 +42,7 @@ func GetConnection() *investgo.Client { mutex_Connect.RLock() defer mutex_Connect.RUnlock() + // if Client == nil { err := Connect_err() LogInfo_Connected(err)