-
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathexample_wrap_dbs_mutli_primary_multi_replicas_test.go
70 lines (61 loc) · 2.09 KB
/
example_wrap_dbs_mutli_primary_multi_replicas_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package dbresolver_test
import (
"context"
"database/sql"
"fmt"
"log"
"github.com/bxcodec/dbresolver/v2"
_ "github.com/lib/pq"
)
func ExampleNew_multiPrimaryMultiReplicas() {
var (
host1 = "localhost"
port1 = 5432
user1 = "postgresrw"
password1 = "<password>"
host2 = "localhost"
port2 = 5433
user2 = "postgresro"
password2 = "<password>"
dbname = "<dbname>"
)
// connection string
rwPrimary := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host1, port1, user1, password1, dbname)
readOnlyReplica := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host2, port2, user2, password2, dbname)
// open database for primary
dbPrimary1, err := sql.Open("postgres", rwPrimary)
if err != nil {
log.Print("go error when connecting to the DB")
}
// open database for primary
dbPrimary2, err := sql.Open("postgres", rwPrimary)
if err != nil {
log.Print("go error when connecting to the DB")
}
// configure the DBs for other setup eg, tracing, etc
// eg, tracing.Postgres(dbPrimary)
// open database for replica
dbReadOnlyReplica1, err := sql.Open("postgres", readOnlyReplica)
if err != nil {
log.Print("go error when connecting to the DB")
}
// open database for replica
dbReadOnlyReplica2, err := sql.Open("postgres", readOnlyReplica)
if err != nil {
log.Print("go error when connecting to the DB")
}
// configure the DBs for other setup eg, tracing, etc
// eg, tracing.Postgres(dbReadOnlyReplica)
connectionDB := dbresolver.New(
dbresolver.WithPrimaryDBs(dbPrimary1, dbPrimary2),
dbresolver.WithReplicaDBs(dbReadOnlyReplica1, dbReadOnlyReplica2),
dbresolver.WithLoadBalancer(dbresolver.RoundRobinLB))
// now you can use the connection for all DB operation
_, err = connectionDB.ExecContext(context.Background(), "DELETE FROM book WHERE id=$1") // will use primaryDB
if err != nil {
log.Print("go error when executing the query to the DB", err)
}
_ = connectionDB.QueryRowContext(context.Background(), "SELECT * FROM book WHERE id=$1") // will use replicaReadOnlyDB
// Output:
//
}