go cassandra 示例2


本文摘自网络,作者,侵删。

建立连接,参数配置(说明:下文中golangConfig.InitConfigMap为项目启动时加载的配置文件,读取成全局的Map)

package cassandra

import (
	"fmt"
	"github.com/gocql/gocql"
	"time"
	"src/golangConfig"
)

var (
	// connect to the cluster
	CassandraSession        *gocql.Session
	cluster                 *gocql.ClusterConfig
	CassandraSessionBatch   *gocql.Batch
	clusterCreateSessionErr error
	CassandraInsertCql      string
)

func CassandraConnectInit() {
	CassandraInsertCql = "INSERT INTO " + golangConfig.InitConfigMap["cassandraTable"].(string) + " (srcIp, .....,uuid) VALUES (?,?,?,?,?,?,?,?,?,?,?,?) "
	cluster = gocql.NewCluster()
	cluster.Keyspace = golangConfig.InitConfigMap["cassandraKeyspace"].(string)
	hosts := []string{golangConfig.InitConfigMap["cassandraServiceUrl"].(string)}
	cluster.Hosts = hosts
	cluster.ConnectTimeout = golangConfig.InitConfigMap["cassandraConnectTimeout"].(time.Duration)
	cluster.Timeout = golangConfig.InitConfigMap["cassandraTimeout"].(time.Duration)
	cluster.Consistency = gocql.Quorum
	cluster.NumConns = golangConfig.InitConfigMap["cassandraNumConns"].(int)
	cluster.Consistency = gocql.One
	CassandraSession, clusterCreateSessionErr = cluster.CreateSession()
	if clusterCreateSessionErr != nil {
		panic(clusterCreateSessionErr)
	}

}

func CassandraSessionBatchInit() *gocql.Batch {
	CassandraSessionBatch = CassandraSession.NewBatch(gocql.UnloggedBatch)
	return CassandraSessionBatch
}

func InsertCassandraMany(batch1 *gocql.Batch) {
	if err := CassandraSession.ExecuteBatch(batch1); err != nil {
		fmt.Println("execute batch:", err)
	}
}

连接初始化,在Main方法中调用

dbwrite.CassandraInit()

阅读剩余部分

相关阅读 >>

Golang 四则运算 计算器 yacc 归约

Go学习六·集合(map)

Golang中map与并发

devops ci/cd 分析(三)之k8s yaml模版配置详解

Golang中的map是结构体吗

ketos 笔记 -- 记 Go hackathon 2017

Go语言两种版本的hello world你会吗

Golang 异常处理 在defer中通过recover捕获异常

Go语言指针数组

Golang语言学习之什么是Golang

更多相关阅读请进入《Go》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...

    暂无评论...