virsas-mod-sql
Quick way to init mysql, postgres and redis connection from multiple services without duplicating the code.
Available functions
- InitMysqlDB
- InitPostgresDB
- InitRedisDB
Passed variables
Mysql and Postgres functions will take following variables:
- user (string)
- password (string)
- hostname (string)
- port (int)
- database (string)
Redis function will take:
- password (string)
- hostname (string)
- port (int)
- dbid (int)
As environmental variables, one can pass some fine tunning for mysql connection
export VSS_DB_MYSQL_MAX_OPEN_CONNECTIONS="25"
export VSS_DB_MYSQL_MAX_IDLE_CONNECTIONS="25"
As environmental variables, one can pass some fine tunning for postgres connection
export VSS_DB_PSQL_MAX_OPEN_CONNECTIONS="25"
export VSS_DB_PSQL_MAX_IDLE_CONNECTIONS="25"
usage - mysql
import (
...
"github.com/virsas/vssdb"
...
)
func main() {
...
maindb, err := vssdb.InitMysqlDB("user123", "password123", "example.com", 3306, "accounts")
if err != nil {
log.Panic(err)
}
var id int64
err = maindb.QueryRow("SELECT id FROM users LIMIT 1;").Scan(&id)
if err != nil {
log.Panic(err)
}
fmt.Println(id)
}
usage - redis
import (
...
"github.com/virsas/vssdb"
...
)
func main() {
...
redisDB, _, err := vssdb.InitRedisDB("", "localhost", 6379, 1)
if err != nil {
log.Panic(err)
}
err = redisDB.Set("name", "Virsas", 0).Err()
if err != nil {
log.Panic(err)
}
name, err := redisDB.Get("name").Result()
if err != nil {
fmt.Println(err)
}
fmt.Println(name)
}
usage - redis - pub/sub
import (
...
"github.com/virsas/vssdb"
...
)
func main() {
...
redisDB, ctx, err := vssdb.InitRedisDB("", "localhost", 6379, 1)
if err != nil {
log.Panic(err)
}
# ...
pubsub := redisDB.Subscribe(ctx, 123)
# ...
err := redisDB.Publish(ctx, 123, message).Err()
if err != nil {
log.Println(err)
}
# ...
}