dounanyin3179
dounanyin3179
2016-08-16 17:54

如何用GO语言创建持久的cassandra连接?

  • cassandra
已采纳

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()
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doutuan9357 doutuan9357 5年前
    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.

    点赞 评论 复制链接分享

为你推荐