Daisy
Daisy

Reputation: 53

How to create persistent cassandra connection in GO language?

I am trying to learn GO language. In my small project, making Cassandra DB connection but its taking more time to create session.

I want to create persistent connection so that from next hit, connection time will be equal to negligible.

Is any method to create persistent connection?

Cassandra connection code is below:

cluster := gocql.NewCluster("cluseter_ip")
pass := gocql.PasswordAuthenticator{"username", "password"}
cluster.Keyspace = "keyspace_name"
cluster.Authenticator = pass
cluster.Consistency = gocql.One
cluster.Port = 9042   // default port 
cluster.NumConns = 1
session, _ := cluster.CreateSession()

Upvotes: 2

Views: 1543

Answers (1)

Anupam
Anupam

Reputation: 887

var session *gocql.Session

func getCluster() *gocql.ClusterConfig {
     cluster := gocql.NewCluster("cluseter_ip")
     pass := gocql.PasswordAuthenticator{"username", "password"}
     cluster.Keyspace = "keyspace_name"
     cluster.Authenticator = pass
     cluster.Consistency = gocql.One
     cluster.Port = 9042   // default port 
     cluster.NumConns = 1
     return cluster
}

func initSession() error {
    var err error
    if session == nil || session.Closed() {
        session, err := getCluster().CreateSession()
    }
    return err
}

Now before using session, call initSession() and check for error before using it. Something like this should work. If your application is multithreaded, make sure to synchronize initSession api.

Upvotes: 3

Related Questions