gocassandrareconnectgocql

Constantly Reconnect to Cassandra


I have read online that the best practice when using Cassandra is to have 1 Cluster and 1 Session for the lifetime of your service.

My questions are:

  1. In case our Cassandra server goes down, how do I make sure that my Cluster and/or Session will keep trying to reconnect until our Cassandra server gets back online?

  2. Should only the Cluster attempt to reconnect, or only the Session, or both?

We are using Go and github.com/gocql/gocql for our service.

I have seen the following snippet in the gocql documentation, but it looks like it only has a limited number of retries:

cluster.ReconnectionPolicy = &gocql.ConstantReconnectionPolicy{MaxRetries: 10, Interval: 8 * time.Second}

I also found the below snippet online, but it doesn't look like it's designed to handle this scenario:

var cluster *gocql.ClusterConfig
var session *gocql.Session

func getCassandraSession() *gocql.Session {
    if session == nil || session.Closed() {
        if cluster == nil {
            cluster = gocql.NewCluster("127.0.0.1:9042")
            cluster.Keyspace = "demodb"
            cluster.Consistency = gocql.One
            cluster.ProtoVersion = 4
        }
        var err error
        if session, err = cluster.CreateSession(); err != nil {
            panic(err)
        }
    }
    return session
}

Are any of the above methods sufficient to ensure that reconnections are attempted until our Cassandra server gets back online? And if not, what's the best practice for this scenario?


Solution

  • Special thanks to @Jim Wartnick for this. I just tried turning Cassandra off on my local machine and then turning it back on and gocql instantly reconnected without having to use any of the above snippets in my question.

    As long as your Cluster and Session have connected to Cassandra at least once, even if Cassandra goes down, they will instantly reconnect to it as soon as Cassandra gets back online.

    Many thanks to everyone who helped!