Prefer the specific availability zone
Note
The article is being updated.
Below are examples of the code for setting the "prefer the availability zone" balancing algorithm option in different YDB SDKs.
Go (native)
Go (database/sql)
package main
import (
"context"
"os"
"github.com/ydb-platform/ydb-go-sdk/v3"
"github.com/ydb-platform/ydb-go-sdk/v3/balancers"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
db, err := ydb.Open(ctx,
os.Getenv("YDB_CONNECTION_STRING"),
ydb.WithBalancer(
balancers.PreferLocations(
balancers.RandomChoice(),
"a",
"b",
),
),
)
if err != nil {
panic(err)
}
defer db.Close(ctx)
...
}
Client load balancing in the YDB database/sql
driver is performed only when establishing a new connection (in database/sql
terms), which is a YDB session on a specific node. Once the session is created, all queries in this session are passed to the node where the session was created. Queries in the same YDB session are not balanced between different YDB nodes.
Example of the code for setting the "prefer the availability zone":
package main
import (
"context"
"database/sql"
"os"
"github.com/ydb-platform/ydb-go-sdk/v3"
"github.com/ydb-platform/ydb-go-sdk/v3/balancers"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
nativeDriver, err := ydb.Open(ctx,
os.Getenv("YDB_CONNECTION_STRING"),
ydb.WithBalancer(
balancers.PreferLocations(
balancers.RandomChoice(),
"a",
"b",
),
),
)
if err != nil {
panic(err)
}
defer nativeDriver.Close(ctx)
connector, err := ydb.Connector(nativeDriver)
if err != nil {
panic(err)
}
db := sql.OpenDB(connector)
defer db.Close()
...
}