Was this page helpful?
Connecting to the cluster¶
Create one Session during application startup and share it across goroutines.
A session discovers cluster topology, maintains connection pools, and routes
concurrent requests. Creating a session per request wastes connections and
discovery work.
Supply several reachable contact points when possible:
cluster := gocql.NewCluster(
"192.0.2.10:9042",
"192.0.2.11:9042",
"192.0.2.12:9042",
)
cluster.Keyspace = "application"
session, err := cluster.CreateSession()
if err != nil {
return err
}
defer session.Close()
Contact points bootstrap discovery; they are not the complete list of hosts used by the session. Prefer node broadcast addresses or IP addresses. DNS names that resolve to multiple addresses can make topology events difficult to match to discovered hosts.
Reconnection policies¶
Reconnection policies restore failed host connections; they do not retry queries. Configure steady-state and initial connection behavior separately:
cluster.ReconnectionPolicy = &gocql.ExponentialReconnectionPolicy{
MaxRetries: 10,
InitialInterval: time.Second,
MaxInterval: 30 * time.Second,
}
cluster.InitialReconnectionPolicy = &gocql.ConstantReconnectionPolicy{
MaxRetries: 5,
Interval: 2 * time.Second,
}
NoReconnectionPolicy performs only the initial connection attempt. A custom
policy must return a positive maximum attempt count.