Database 在go postgress中连接多个数据库的最佳方式
我正在开发一个网站生成器,并将每个网站数据存储在单独的数据库中。Database 在go postgress中连接多个数据库的最佳方式,database,postgresql,go,Database,Postgresql,Go,我正在开发一个网站生成器,并将每个网站数据存储在单独的数据库中。 我的问题是如何正确有效地处理多个数据库连接。 所有数据库和代码都在同一个服务器中我创建了自己的连接到多个连接数据库的方法 首先,我为以下对象创建基础文件: 然后调用它来创建连接列表,如: 最后从映射调用所有连接: //getting list of all the connection. listConnection := database.SystemConnection() //getting red
我的问题是如何正确有效地处理多个数据库连接。
所有数据库和代码都在同一个服务器中我创建了自己的连接到多个连接数据库的方法 首先,我为以下对象创建基础文件: 然后调用它来创建连接列表,如: 最后从映射调用所有连接:
//getting list of all the connection.
listConnection := database.SystemConnection()
//getting redis connection convert it from interface to *redisClient.
redisConn := listConnection["redis"].(*redis.Client)
// get postgre connection.
postgreConn := listConnection["postgre"].(*sqlx.DB)
postgreConn2 := listConnection["postgre2"].(*sqlx.DB)
您可以从中获取所有源代码。它仍在进展中,但希望你能得到这个想法。希望有帮助。- 具有表示站点的上下文结构
- 此上下文结构保存数据库连接
- 当一个用户登录时,还要为他/她设置哪个站点处于活动状态(我假设一个用户帐户可以有多个站点)
- 当用户访问服务器时,检查站点的cookie
- 根据从cookie中获得的站点名称,小心地使用互斥从全局列表/映射(映射将是
)中获取上下文map[string]context
- 如果上下文不存在,请实例化一个。在内部,它创建到DB的连接,连接到站点的相应表,并将自己注册到全局列表(使用互斥)
- 在每个上下文实例中,都有一个特定分钟的计时器,该计时器在被访问时重置。当它超时(即,在某些分钟内未被访问)或最后一个拥有该站点的用户注销时,它将从全局列表中删除自己(再次使用互斥)并断开其数据库连接
//we create different types of databse connection here
func SystemConnection() map[string]interface{} {
listConnection := make(map[string]interface{})
var err error
// create redis connection
redisConn := RedisHost{
Address: "localhost:6379",
Password: "",
DB: 0,
}
redisConnection, err := redisConn.Connect()
if err != nil {
panic(err)
}
// create postgre connection
postgreConn := PostgreHost{
Driver: "postgres",
Database: "postgres",
Username: "postgres",
Ssl: "disable",
Password: "root",
}
// you can create your another connection here :
postgreConn2 := PostgreHost{
Driver: "postgres",
Database: "postgres",
Username: "postgres",
Ssl: "disable",
Password: "root",
}
postgreConnection, err := GetPostgreDb(&postgreConn)
if err != nil {
panic(err)
}
postgreConnection2, err := GetPostgreDb(&postgreConn2)
if err != nil {
panic(err)
}
listConnection["redis"] = redisConnection
listConnection["postgre"] = postgreConnection
listConnection["postgre2"] = postgreConnection2
return listConnection
}
//getting list of all the connection.
listConnection := database.SystemConnection()
//getting redis connection convert it from interface to *redisClient.
redisConn := listConnection["redis"].(*redis.Client)
// get postgre connection.
postgreConn := listConnection["postgre"].(*sqlx.DB)
postgreConn2 := listConnection["postgre2"].(*sqlx.DB)