关于什么是cassandra,可以参考:

http://blog.csdn.net/zyz511919766/article/details/38683219

http://cassandra.apache.org/

比较了HBASE、mongodb 和 cassandra

1)HBASE 和 cassandra 都是列式存储,但是 cassandra部署方便,扩展容易
2) mongodb 并不是真正的列式存储,数据扩容比较麻烦,需要提前做好集群分区

casandra是 p2p(gossip)实现的bigtable,  数据一致性可以通过参数配置(R+W >N),  写操作完成是all node,还是指定的node个数,才进行返回。

数据模型:

尝试了cassandra的两个client。

1. "github.com/gocql/gocql"

2."github.com/hailocab/gocassa"

gocassa是在gocql上面的封装,提供更方便的操作。

在用cassandra之前,建议先熟悉一下CQL,类似 SQL语句的语法。

作为一个client, 我们需要考虑的点:

1)连接池

2)批量操作

3)可能还会考虑同步操作(同时更新两个table中的数据)

cassandra部署和使用都还算简单,比较困难的是,要摆脱传统的db设计范式思维,要根据后续的数据查询来设计你的bigtable结构,方便将来的查询。

贴上几个相关的参考资料:

http://www.slideshare.net/yukim/cql3-in-depth (CQL相关介绍)
http://www.slideshare.net/jaykumarpatel/cassandra-data-modeling-best-practices
http://www.infoq.com/cn/articles/best-practices-cassandra-data-model-design-part2 (ebay的cassandra实践)

然后,贴上两个client使用示例:

package main

import (
"fmt"
"log"
"time" "github.com/gocql/gocql"
) func main() {
// connect to the cluster
cluster := gocql.NewCluster("127.0.0.1")
cluster.Keyspace = "demo"
cluster.Consistency = gocql.Quorum
//设置连接池的数量,默认是2个(针对每一个host,都建立起NumConns个连接)
cluster.NumConns = session, _ := cluster.CreateSession()
time.Sleep( * time.Second) //Sleep so the fillPool can complete.
fmt.Println(session.Pool.Size())
defer session.Close() //unlogged batch, 进行批量插入,最好是partition key 一致的情况
t := time.Now()
batch := session.NewBatch(gocql.UnloggedBatch)
for i := ; i < ; i++ {
batch.Query(`INSERT INTO bigrow (rowname, iplist) VALUES (?,?)`, fmt.Sprintf("name_%d", i), fmt.Sprintf("ip_%d", i))
}
if err := session.ExecuteBatch(batch); err != nil {
fmt.Println("execute batch:", err)
}
bt := time.Now().Sub(t).Nanoseconds() t = time.Now()
for i := ; i < ; i++ {
session.Query(`INSERT INTO bigrow (rowname, iplist) VALUES (?,?)`, fmt.Sprintf("name_%d", i), fmt.Sprintf("ip_%d", i))
}
nt := time.Now().Sub(t).Nanoseconds() t = time.Now()
sbatch := session.NewBatch(gocql.UnloggedBatch)
for i := ; i < ; i++ {
sbatch.Query(`INSERT INTO bigrow (rowname, iplist) VALUES (?,?)`, "samerow", fmt.Sprintf("ip_%d", i))
}
if err := session.ExecuteBatch(sbatch); err != nil {
fmt.Println("execute batch:", err)
}
sbt := time.Now().Sub(t).Nanoseconds()
fmt.Println("bt:", bt, "sbt:", sbt, "nt:", nt) //----------out put------------------
// ./rawtest
// bt: 5795593 sbt: 3003774 nt: 261775
//------------------------------------ // insert a tweet
if err := session.Query(`INSERT INTO tweet (timeline, id, text) VALUES (?, ?, ?)`,
"me", gocql.TimeUUID(), "hello world").Exec(); err != nil {
log.Fatal(err)
} var id gocql.UUID
var text string /* Search for a specific set of records whose 'timeline' column matches
* the value 'me'. The secondary index that we created earlier will be
* used for optimizing the search */
if err := session.Query(`SELECT id, text FROM tweet WHERE timeline = ? LIMIT `,
"me").Consistency(gocql.One).Scan(&id, &text); err != nil {
log.Fatal(err)
}
fmt.Println("Tweet:", id, text) // list all tweets
iter := session.Query(`SELECT id, text FROM tweet WHERE timeline = ?`, "me").Iter()
for iter.Scan(&id, &text) {
fmt.Println("Tweet:", id, text)
}
if err := iter.Close(); err != nil {
log.Fatal(err)
} query := session.Query(`SELECT * FROM bigrow where rowname = ?`, "")
// query := session.Query(`SELECT * FROM bigrow `) var m map[string]interface{}
m = make(map[string]interface{}, )
err := query.Consistency(gocql.One).MapScan(m)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%#v", m)
}
package main

import (
"fmt"
"time" "github.com/hailocab/gocassa"
) // This test assumes that cassandra is running on default port locally and
// that the keySpace called 'test' already exists. type Sale struct {
Id string
CustomerId string
SellerId string
Price int
Created time.Time
} func main() { keySpace, err := gocassa.ConnectToKeySpace("not_exist_demo", []string{"127.0.0.1"}, "", "") if err != nil {
panic(err)
}
salesTable := keySpace.Table("sale", Sale{}, gocassa.Keys{
PartitionKeys: []string{"Id"},
}) // Create the table - we ignore error intentionally
err = salesTable.Create()
fmt.Println(err)
// We insert the first record into our table - yay!
err = salesTable.Set(Sale{
Id: "sale-1",
CustomerId: "customer-1",
SellerId: "seller-1",
Price: ,
Created: time.Now(),
}).Run()
if err != nil {
panic(err)
} result := Sale{}
if err := salesTable.Where(gocassa.Eq("Id", "sale-1")).ReadOne(&result).Run(); err != nil {
panic(err)
}
fmt.Println(result)
}

更多配置可参考:

https://github.com/gocql/gocql/blob/master/cluster.go#L57

// ClusterConfig is a struct to configure the default cluster implementation
// of gocoql. It has a varity of attributes that can be used to modify the
// behavior to fit the most common use cases. Applications that requre a
// different setup must implement their own cluster.
type ClusterConfig struct {
Hosts []string // addresses for the initial connections
CQLVersion string // CQL version (default: 3.0.0)
ProtoVersion int // version of the native protocol (default: 2)
Timeout time.Duration // connection timeout (default: 600ms)
Port int // port (default: 9042)
Keyspace string // initial keyspace (optional)
NumConns int // number of connections per host (default: 2)
NumStreams int // number of streams per connection (default: max per protocol, either 128 or 32768)
Consistency Consistency // default consistency level (default: Quorum)
Compressor Compressor // compression algorithm (default: nil)
Authenticator Authenticator // authenticator (default: nil)
RetryPolicy RetryPolicy // Default retry policy to use for queries (default: 0)
SocketKeepalive time.Duration // The keepalive period to use, enabled if > 0 (default: 0)
ConnPoolType NewPoolFunc // The function used to create the connection pool for the session (default: NewSimplePool)
DiscoverHosts bool // If set, gocql will attempt to automatically discover other members of the Cassandra cluster (default: false)
MaxPreparedStmts int // Sets the maximum cache size for prepared statements globally for gocql (default: 1000)
MaxRoutingKeyInfo int // Sets the maximum cache size for query info about statements for each session (default: 1000)
PageSize int // Default page size to use for created sessions (default: 5000)
SerialConsistency SerialConsistency // Sets the consistency for the serial part of queries, values can be either SERIAL or LOCAL_SERIAL (default: unset)
Discovery DiscoveryConfig
SslOpts *SslOptions
DefaultTimestamp bool // Sends a client side timestamp for all requests which overrides the timestamp at which it arrives at the server. (default: true, only enabled for protocol 3 and above)
}
连接池,默认采用是NewSimplePool,这里用的是roud robin
源码:https://github.com/gocql/gocql/blob/master/connectionpool.go#L454
ConnPoolType 是一个接口,可以自己实现接口来定制话自己的策略。
数据一致性策略,通过Consistency配置,默认是Quorum(大部分节点):
type Consistency uint16

const (
Any Consistency = 0x00
One Consistency = 0x01
Two Consistency = 0x02
Three Consistency = 0x03
Quorum Consistency = 0x04
All Consistency = 0x05
LocalQuorum Consistency = 0x06
EachQuorum Consistency = 0x07
LocalOne Consistency = 0x0A
)
 

Cassandra go语言client使用的更多相关文章

  1. Redis:安装、配置、操作和简单代码实例(C语言Client端)

    Redis:安装.配置.操作和简单代码实例(C语言Client端) - hj19870806的专栏 - 博客频道 - CSDN.NET Redis:安装.配置.操作和简单代码实例(C语言Client端 ...

  2. 对比Cassandra、 Mongodb、CouchDB、Redis、Riak、 Membase、Neo4j、HBase

    转自:http://www.cnblogs.com/alephsoul-alephsoul/archive/2013/04/26/3044630.html 导读:Kristóf Kovács 是一位软 ...

  3. C语言使用hiredis访问redis

    Hiredis 是Redis数据库的简约C客户端库.它是简约的,因为它只是增加了对协议的最小支持,但是同时它使用了一个高级别的 printf-like API,所以对于习惯了 printf 风格的C编 ...

  4. HDFS简单介绍及用C语言訪问HDFS接口操作实践

    一.概述 近年来,大数据技术如火如荼,怎样存储海量数据也成了当今的热点和难点问题,而HDFS分布式文件系统作为Hadoop项目的分布式存储基础,也为HBASE提供数据持久化功能,它在大数据项目中有很广 ...

  5. 8种Nosql数据库系统对比

    导读:Kristóf Kovács 是一位软件架构师和咨询顾问,他最近发布了一片对比各种类型NoSQL数据库的文章. 虽然SQL数据库是非常有用的工具,但经历了15年的一支独秀之后垄断即将被打破.这只 ...

  6. 8种NOsql

    虽然SQL数据库是非常有用的工具,但经历了15年的一支独秀之后垄断即将被打破.这只是时间问题:被迫使用关系数据库,但最终发现不能适应需求的情况不胜枚举. 但是NoSQL数据库之间的不同,远超过两 SQ ...

  7. 【转】8种Nosql数据库系统对比

    导读:Kristóf Kovács 是一位软件架构师和咨询顾问,他最近发布了一片对比各种类型nosql数据库的文章.文章由敏捷翻译 – 唐尤华编译.如需转载,请参见文后声明. 虽然SQL数据库是非常有 ...

  8. thrift 安装介绍

    一.About  thrift            thrift是一种可伸缩的跨语言服务的发展软件框架.它结合了功能强大的软件堆栈的代码生成引擎,以建设服务,工作效率和无缝地与C + +,C#,Ja ...

  9. Data Base 关于nosql的讲解

    Data Base  关于nosql的讲解 nosql非关系型数据库. 优点: 1.可扩展 2.大数据量,高性能 3.灵活的数据模型 4.高可用 缺点: 1.不正式 2.不标准 非关系型数据库有哪些: ...

随机推荐

  1. 基于jQuery的图片异步加载和预加载实例

    如今的网页中有很多图片,比如相册列表,那么如果一次性读取图片将会瞬间加重服务器的负担,所以我们用jQuery来实现图片的异步加载和预加载功能,这样在页面的可视范围内才会加载图片,当拖动页面至可视界面时 ...

  2. c#第一个程序-计算平方根

    上课教的内容.做笔记了. using System; using System.Collections.Generic; using System.ComponentModel; using Syst ...

  3. 存档格式选择--JSON

    游戏里存档可以直接用lua,但是lua需要有一定编程基础:另外可以用ini,不过ini又太简单了,复杂的 格式无法用ini描述:还可以用xml,它的表达能力非常丰富,甚至有限数据库都用xml来作存储结 ...

  4. PHP——转义字符

    链接:百度-转义字符 http://baike.baidu.com/link?url=obfdOqATx4TO0Ev_kFnPz37wwW3SDhFPsvNobVTidhFuCn2zK5VmCuW1L ...

  5. netifd

    Netifd是OpenWrt中用于进行网络配置的守护进程,基本上所有网络接口设置以及内核的netlink事件都可以由netifd来处理完成. 在启动netifd之前用户需要将所需的配置写入uci配置文 ...

  6. SSIS 自测题-数据流控件类

    说明:以下是自己的理解答案,不是标准的答案,如有不妥烦请指出.         有些题目暂时没有答案,有知道的请留言,互相学习,一起进步. 133.请描述一下 Conditional Split 的使 ...

  7. IOC控制反转

    IOC是Inversion of Control的缩写,多数书籍翻译成“控制反转”,还有些书籍翻译成为“控制反向”或者“控制倒置”.     1996年,Michael Mattson在一篇有关探讨面 ...

  8. Differential Geometry之第七章曲面的若干整体性质

    1.曲面的整体描述 2.整体的Gauss-Bonnet公式 2.1.曲面的三角剖分 2.2.Gauss-Bonnet公式 = 2.3.Gauss-Bonnet定理的应用 2.3.1.切向量场的指数定理 ...

  9. 假设A.jsp内设定一个<jsp:useBean>元素:

    假设A.jsp内设定一个<jsp:useBean>元素: <jsp:useBean id=”bean1” class=”myBean” /> 下列哪一个为真?(选择1项) A. ...

  10. duilib Webkit内核dui化浏览器控件

    參考http://blog.csdn.net/zhuhongshu/article/details/38540711 改进: 1.跟其它duilib控件一样,不包括窗体 2.将onURLChanged ...