性能测试:SequoiaDB vs. MongoDB vs. Cassandra vs. HBase

allowtransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?url=http%3A%2F%2Fwww.csdn.net%2Farticle%2F2014-09-16%2F2821707-benchmark-test-of-MongoDB-SequoiaDB-HBase-Cassandra%2F1&type=3&count=&appkey=&title=NoSQL%E9%80%9A%E8%BF%87%E5%BC%B1%E5%8C%96%E4%B8%80%E9%83%A8%E5%88%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%89%B9%E6%80%A7%EF%BC%88%E5%A6%82%E4%B8%80%E8%87%B4%E6%80%A7%E5%92%8C%E5%85%B3%E7%B3%BB%E6%A8%A1%E5%9E%8B%EF%BC%89%E6%9D%A5%E6%8F%90%E5%8D%87%E5%85%B6%E5%8F%AF%E6%89%A9%E5%B1%95%E6%80%A7%E5%8F%8A%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%A7%EF%BC%8C%E5%BC%A5%E8%A1%A5%E4%BA%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9C%A8%E5%BE%88%E5%A4%9A%E4%BA%92%E8%81%94%E7%BD%91%E7%B1%BB%E5%BA%94%E7%94%A8%E4%B8%AD%E7%9A%84%E4%B8%8D%E8%B6%B3%E3%80%82%E5%9B%A0%E6%AD%A4%EF%BC%8C%E4%B8%8D%E5%90%8C%E7%9A%84NoSQL%E6%9C%89%E7%9D%80%E4%B8%8D%E5%90%8C%E7%9A%84%E6%9D%80%E6%89%8B%E7%BA%A7%E5%BA%94%E7%94%A8%EF%BC%8C%E8%BF%99%E9%87%8C%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E5%9F%BA%E5%87%86%E6%B5%8B%E8%AF%95%E6%91%B8%E7%B4%A2%E3%80%82&pic=&ralateUid=&language=zh_cn&rnd=1411610910647" width="22" height="16"> 摘要:NoSQL通过弱化一部分关系型数据库特性(如一致性和关系模型)来提升其可扩展性及高可用性,弥补了关系型数据库在很多互联网类应用中的不足。因此,不同的NoSQL有着不同的杀手级应用,这里我们通过基准测试摸索。

【编者按】在《先锋》系列的 事务、高性能,王涛谈打造超越MongoDB的NoSQL一文中,我们与王涛浅谈了高性能,拥有事务的SequoiaDB打造经验。应读者需求,从数据上解读各个NoSQL的优势,我们同时邀请了国内外相关专家对MongoDB、SequoiaDB、Cassandra、HBase四个NoSQL进行基准测试,并公布测试用例、相关数据及测试规则。本次我们将给大家放出国内专家的测评,仅供参考。PS:为了方便传阅,特别为大家准备了PDF版本,点击下载

下为测试资料

在本篇测试报告中,我们使用Yahoo!发布的标准YCSB测试规则,对MongoDB、SequoiaDB、Cassandra、HBase进行对比,并尝试给出每种不同产品所适用的应用场景。在测试配置中,我们尽可能对全部产品做到高可用配置,而在一致性级别上则使用最终一致性。

在测试中我们会对两种类型的NoSQL数据库做横向对比,包括Document-Oriented文档类数据库、以及Big-Table宽表类数据库。由于每种类型的数据库具有很多自己独特的特性,我们不能将每种特性一一表现在该测评结果中。本测试主要针对数据库在不同任务类型下的性能指标进行,且仅依赖YCSB所提供的标准测试流程。

本测试将详细列出测试的物理环境以及配置信息,以便于读者能够使用自己的环境独立验证结果。

测试概要

1. 测试产品

本测试主要对比两种类型的NoSQL数据库,包括四款不同的产品: 

  • MongoDB(文档类,V2.6.1)
  • SequoiaDB(文档类,V1.8)
  • HBase(宽表类,V0.94.6-CDH 4.5.0)
  • Cassandra(宽表类,V1.1.12)

其中MongoDB作为当前市场占有率最高的数据库,可能是众多读者所关心的产品,提供丰富的数据库功能,号称是最接近关系型数据库的NoSQL产品;而SequoiaDB由前IBM DB2团队的研发人员创建,据称在性能和功能上能够与MongoDB做正面抗衡,同样提供很多MongoDB所提供的功能(例如分片、多索引等特性)。

HBase则是Hadoop框架的一员,也已经被广大企业和互联网用户所接受,我们使用的版本0.94.6是跟随CDH 4.5.0安装包的版本;而Cassandra则是与HBase类似的产品,由Facebook研发并进行开源,同样拥有广大的用户市场。

我们的测试使用由Yahoo!研究院发布的Yahoo Cloud Serving Benchmark (YCSB)基准测试,并将接口对各自产品的最新版进行了修改和适配。我们在正文后的附录中也提供了SequoiaDB的YCSB测试接口。

需要重新强调的是,每种不同的产品都有各自的应用场景。YCSB测试尽管是Yahoo!研究院提供的测试框架,但是在很多场景下并不能完全发挥出每个产品各自的特点。在本测试中,我们尝试使用YCSB框架给出最为客观的评估结果。如果对于该测试结果或配置存在疑问,我们欢迎广大读者根据自身需要重新调整,并将结果开放以供参考。

2. 测试场景

YCSB测试框架提供了丰富的场景配置机制,允许用户根据需要选择需要导入的数据量和增删改查之间相应的比例。在本测试中,我们导入一亿条数据,并对如下场景进行对比。

场景编号 场景分类 描述
1 单条记录导入 单条记录导入
2 批量记录导入 批量记录导入
3 单纯查询 100%查询
4 查询导入平衡 50%导入,50%查询
5 更新为主 95%更新,5%查询
6 查询为主 95%查询,5%更新
7 查询最新 95%查询,5%导入

对于数据导入的场景,我们对单条记录插入和批量插入两个场景进行了区分。对于一些数据库来说,默认配置会在客户端将一批记录打包并统一发送给服务器,对于这类产品,尽管其接口为单条记录操作,我们依然将其归类为批量记录导入模式。

写入和查询的数据模拟典型日志记录的长度,具有以下特性:

特性 描述
字段数 10字段
字段名长度 6字节
记录总大小 100Bytes
全部字段类型 字符串
主键长度 23字节
总记录数 1亿条
总裸数据量 大约100GB
数据副本份数 3

其中,SequoiaDB与MongoDB的分片均配置为一主两从;HBase所在的HDFS设置复制份数为3;Cassandra建表时使用参数replication_factor=2。

一致性级别上,我们使用最弱的最终一致性,读写的write concern均设置为1。

3. 测试环境

本测试中,测试环境总共包含4台Dell R520物理机作为数据存储。生成数据的YCSB程序与数据库运行在同一物理环境。

注:如使用独立服务器进行YCSB的数据生成,会导致千兆网瓶颈。

整个集群的拓扑结构如图1所示:

 

图1:测试集群拓扑 

服务器环境。本测试数据库服务器使用4台Dell R520物理机环境,每台物理机配置如下:

类型 参数
CPU Intel(R) Xeon® CPU E5-2420 1.9GHZ (6 core)
内存 DDR3 48GB
磁盘 6块内置SATA硬盘,2TB/块
网络 千兆以太网
操作系统 Red Hat Enterprise Linux Server release 6.4 
kernel-release:2.6.32-358.e16.x86_64
JDK Oracle JDK 1.6

4. 测试方法

本测试使用YCSB标准,基于四台物理机执行。对于每种不同产品的测试流程如下:

  • 安装软件
  • 基于四节点部署集群,配置时尽可能基于以下准则:

  • 高可用配置
  • 最终一致性
  • 功能与单节点环境保持一致
  • 充分利用硬件资源

  • 在四台物理机中部署YCSB集群,向本地集群写入读取数据
  • 进行数据操作时通过YCSB产生记录的统计数量
  • 根据结果生成Excel文件
  • 针对其他场景重复以上步骤

并发性方面则基于以下规则:

  • 单条记录插入每服务器24条线程
  • 批量记录插入每服务器8条线程
  • 其他所有操作每服务器36条线程
allowtransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?url=http%3A%2F%2Fwww.csdn.net%2Farticle%2F2014-09-16%2F2821707-benchmark-test-of-MongoDB-SequoiaDB-HBase-Cassandra%2F2&type=3&count=&appkey=&title=NoSQL%E9%80%9A%E8%BF%87%E5%BC%B1%E5%8C%96%E4%B8%80%E9%83%A8%E5%88%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%89%B9%E6%80%A7%EF%BC%88%E5%A6%82%E4%B8%80%E8%87%B4%E6%80%A7%E5%92%8C%E5%85%B3%E7%B3%BB%E6%A8%A1%E5%9E%8B%EF%BC%89%E6%9D%A5%E6%8F%90%E5%8D%87%E5%85%B6%E5%8F%AF%E6%89%A9%E5%B1%95%E6%80%A7%E5%8F%8A%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%A7%EF%BC%8C%E5%BC%A5%E8%A1%A5%E4%BA%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9C%A8%E5%BE%88%E5%A4%9A%E4%BA%92%E8%81%94%E7%BD%91%E7%B1%BB%E5%BA%94%E7%94%A8%E4%B8%AD%E7%9A%84%E4%B8%8D%E8%B6%B3%E3%80%82%E5%9B%A0%E6%AD%A4%EF%BC%8C%E4%B8%8D%E5%90%8C%E7%9A%84NoSQL%E6%9C%89%E7%9D%80%E4%B8%8D%E5%90%8C%E7%9A%84%E6%9D%80%E6%89%8B%E7%BA%A7%E5%BA%94%E7%94%A8%EF%BC%8C%E8%BF%99%E9%87%8C%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E5%9F%BA%E5%87%86%E6%B5%8B%E8%AF%95%E6%91%B8%E7%B4%A2%E3%80%82&pic=&ralateUid=&language=zh_cn&rnd=1411610996306" width="22" height="16"> 摘要:NoSQL通过弱化一部分关系型数据库特性(如一致性和关系模型)来提升其可扩展性及高可用性,弥补了关系型数据库在很多互联网类应用中的不足。因此,不同的NoSQL有着不同的杀手级应用,这里我们通过基准测试摸索。

测试结果

一、 场景1:单条记录导入

 

图2:单条记录导入场景

在单条记录导入场景中,SequoiaDB与MongoDB使用insert方法,writeConcern设置为Normal;HBase则设置客户端缓冲区为2KB。而在错误检验方式上,由于是单条记录插入,所以MongoDB必须在每次操作后检测返回值是否成功,因此不可以使用异步插入方式。

在图2的结果中可以看到,单条记录导入操作SequoiaDB最高,总吞吐量可以达到每秒钟近7万。而HBase与Cassandra则比较接近,在5-6万之间。MongoDB在该场景中表现较差,总吞吐量不到每秒1万。

在该场景中,YCSB在4台服务器上各启动24条线程,总共并发量为96线程。

二、 场景2:批量记录导入

 

图3:批量记录导入场景

批量记录导入场景的结果见图3。在该场景中,SequoiaDB与MongoDB使用各自提供的bulk insert方法;HBase则设置client buffer为4MB;Cassandra不提供批量数据导入方式。

在该测试中,批量导入数据为每批次3000条记录,每节点启动8条线程,总数32线程。

测试结果显示,SequoiaDB可以达到每秒钟近19万的导入速度,而MongoDB则与单线程导入的性能接近(1万左右),HBase也没有本质提升。

三、 场景3:单纯查询

图4:单纯查询场景

图4显示单纯随机查询的场景。在该场景中MongoDB表现最为突出,整体吞吐量达到每秒钟8万以上。SequoiaDB和Cassandra类似,大约为MongoDB的一半,在4万至5万之间徘徊。而HBase表现最差,未达到每秒1万的指标。

该场景每台物理服务器使用36条客户端线程,总数144条线程。

四、 场景4:查询导入平衡

 

图5:查询导入平衡场景

该场景主要模拟50%的插入和50%的查询业务(图5)。其中插入业务使用单条记录插入。

最终的结果显示,SequoiaDB的整体表现最优,平均达到每秒钟超过14000TPS,而MongoDB/HBase/Cassandra则比较接近,各自不到10000TPS。

五、 场景5:更新为主

 

图6:更新为主场景

如图6所示,更新为主场景模拟95%更新与5%查询的场景。该场景中,SequoiaDB表现最优,结果介于5万到6万之间每秒。

而MongoDB表现相对较弱,大约在5千每秒左右的数量级。

六、 场景6:查询为主

 

图7:查询为主场景

在查询为主的场景中,模拟95%查询+5%更新。在该测试中,SequoiaDB与Cassandra的性能接近单纯查询的场景,而更新操作对MongoDB的损耗相对较大,使其性能仅不到3万每秒。

HBase在随机读为主的场景下相对较慢。

七、 场景7:查询最新

 

图8:查询最新场景

查询最新场景为95%读+5%插入,并且读取的数据尽可能是刚刚写入的数据。

从图8中可以看出,SequoiaDB对于刚刚写入至内存中便读取的场景性能最佳,达到近4万每秒。

而MongoDB和Cassandra则相比场景6有明显下降,HBase依然性能较低。

结论

从第三部分的各个场景对比中可以看出,SequoiaDB数据库在数据插入场景中表现最为突出,甚至超过本身以插入性能著称的Cassandra,混合读写场景下性能也可圈可点。而业界普及率最高的MongoDB则在单纯读取性能上最为抢眼,远超其他。

HBase与Cassandra虽然在写入性能上远高于MongoDB,但是和SequoiaDB相比仍然逊色一筹;而在主键随机读操作方面,Cassandra的新版本和之前的版本比起来性能大幅度上升,基本做到和MongoDB处于同一水平线,而HBase则远不能和其他产品相比。

当然,这些比较也仅仅局限于YCSB所做的测试,而文档类数据库能够提供的二级索引等机制并非是YCSB所测试的。因此,文档类数据库能够提供比宽表类数据库更多的应用场景。

如此看来,对于宽表类数据库来说,如果在其最有优势的主场都败给了文档类数据库,这是否意味着,HBase和Cassandra最大的优势已经不再,文档类数据库会在各个领域的性能表现超越宽表呢?

allowtransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?url=http%3A%2F%2Fwww.csdn.net%2Farticle%2F2014-09-16%2F2821707-benchmark-test-of-MongoDB-SequoiaDB-HBase-Cassandra%2F3&type=3&count=&appkey=&title=NoSQL%E9%80%9A%E8%BF%87%E5%BC%B1%E5%8C%96%E4%B8%80%E9%83%A8%E5%88%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%89%B9%E6%80%A7%EF%BC%88%E5%A6%82%E4%B8%80%E8%87%B4%E6%80%A7%E5%92%8C%E5%85%B3%E7%B3%BB%E6%A8%A1%E5%9E%8B%EF%BC%89%E6%9D%A5%E6%8F%90%E5%8D%87%E5%85%B6%E5%8F%AF%E6%89%A9%E5%B1%95%E6%80%A7%E5%8F%8A%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%A7%EF%BC%8C%E5%BC%A5%E8%A1%A5%E4%BA%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9C%A8%E5%BE%88%E5%A4%9A%E4%BA%92%E8%81%94%E7%BD%91%E7%B1%BB%E5%BA%94%E7%94%A8%E4%B8%AD%E7%9A%84%E4%B8%8D%E8%B6%B3%E3%80%82%E5%9B%A0%E6%AD%A4%EF%BC%8C%E4%B8%8D%E5%90%8C%E7%9A%84NoSQL%E6%9C%89%E7%9D%80%E4%B8%8D%E5%90%8C%E7%9A%84%E6%9D%80%E6%89%8B%E7%BA%A7%E5%BA%94%E7%94%A8%EF%BC%8C%E8%BF%99%E9%87%8C%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E5%9F%BA%E5%87%86%E6%B5%8B%E8%AF%95%E6%91%B8%E7%B4%A2%E3%80%82&pic=&ralateUid=&language=zh_cn&rnd=1411611021125" width="22" height="16"> 摘要:NoSQL通过弱化一部分关系型数据库特性(如一致性和关系模型)来提升其可扩展性及高可用性,弥补了关系型数据库在很多互联网类应用中的不足。因此,不同的NoSQL有着不同的杀手级应用,这里我们通过基准测试摸索。

附录A:配置信息

1. MongoDB

MongoDB的分片分布如图9,不同颜色代表不同的分片,我们采用的是多个副本的分片

 

MongoDB的部署脚本如下(deploy.sh): 

[xml]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #!/bin/bash  
  2. ssh perftest-1 "mongod --configsvr --logpath /data/disk1/mongodb-cfg/configsvr.log --dbpath /data/disk1/mongodb-cfg/ --port 37019 --journal --fork"  
  3. ssh perftest-2 "mongod --configsvr --logpath /data/disk1/mongodb-cfg/configsvr.log --dbpath /data/disk1/mongodb-cfg/ --port 37019 --journal --fork"  
  4. ssh perftest-3 "mongod --configsvr --logpath /data/disk1/mongodb-cfg/configsvr.log --dbpath /data/disk1/mongodb-cfg/ --port 37019 --journal --fork"  
  5.   
  6. ssh perftest-1 "mongos --configdb perftest-0:37019,perftest-1:37019,perftest-2:37019 --logpath /data/disk1/mongodb-data/mongos.log --fork"  
  7. ssh perftest-2 "mongos --configdb perftest-0:37019,perftest-1:37019,perftest-2:37019 --logpath /data/disk1/mongodb-data/mongos.log --fork"  
  8. ssh perftest-3 "mongos --configdb perftest-0:37019,perftest-1:37019,perftest-2:37019 --logpath /data/disk1/mongodb-data/mongos.log --fork"  
  9. ssh perftest-4 "mongos --configdb perftest-0:37019,perftest-1:37019,perftest-2:37019 --logpath /data/disk1/mongodb-data/mongos.log --fork"  
  10.   
  11.   
  12. hostno=0  
  13. hosts=("perftest-1" "perftest-2" "perftest-3" "perftest-4")  
  14. disknos=(1 1 1 1)  
  15. port=37017  
  16. for((i=0;i<8;++i))  
  17. do  
  18.    for ((j=0;j<3;++j))  
  19.    do  
  20.      ssh ${hosts[$hostno]} "mongod --replSet dg$i --logpath /data/disk${disknos[$hostno]}/mongodb-data/mongd.log --dbpath /data/disk${disknos[$hostno]}/mongodb-data/ --logappend --quiet --port $port --fork"  
  21.   
  22.       let disknos[$hostno]=${disknos[$hostno]}+1  
  23.       let hostno=hostno+1  
  24.       if [ $hostno -eq ${#hosts[@]} ];then  
  25.          let hostno=0  
  26.       fi  
  27.    done  
  28.    let port=port+10  
  29.   
  30. done  
MongoDB的分片添加脚本如下(addshard.js): 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. var port=37017  
  2. var hosts=[" perftest-1"," perftest-2"," perftest-3"," perftest-4"];  
  3. var hostid=0;  
  4. for(i=0;i<8;++i)  
  5. {  
  6.    var conf = new Object();  
  7.    conf._id = 'dg'+i;  
  8.    conf.members = new Array();  
  9.    for (j=0;j<3;++j)  
  10.    {  
  11.       var member = new Object();  
  12.       member._id = j;  
  13.       member.host = hosts[hostid] + ":" + port;  
  14.       conf.members[j] = member;  
  15.       hostid=hostid+1;  
  16.       if (hostid == hosts.length)  
  17.       {  
  18.          hostid = 0;  
  19.       }  
  20.    }  
  21.   var db = connect(conf.members[0].host +"/test");  
  22.   rs.initiate(conf);  
  23.   rs.conf();  
  24.   port = port + 10  
  25.   var db2 = connect(conf.members[0].host + '/test');  
  26.   sh.addShard('dg'+i+'/'+conf.members[0].host )  
  27. }  
MongoDB的集合创建脚本如下(createcl.sh): 

[js]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. mongo <<EOF  
  2. sh.stopBalancer();  
  3. use ycsb;  
  4. db.dropDatabase();  
  5. use admin;  
  6. db.runCommand({enableSharding:"ycsb"});  
  7. use admin;  
  8. db.runCommand({shardcollection:"ycsb.usertable",key:{_id:'hashed'},numInitialChunks:4096});  
  9. exit  
  10. EOF  

所有的writeConcern都为normal。

2. SequoiaDB

SequoiaDB的数据组分布情况如图10,其中不同颜色代表不同的分片。

SequoiaDB的部署脚本如下(deploy.js): 

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. try  
  2. {  
  3.    var db = new Sdb();  
  4.    db.createCataRG('perftest-1',11820,'/opt/sequoiadb/database/cata/11820');  
  5.    db.getRG(1).createNode('perftest-2',11820,'/opt/sequoiadb/database/cata/11820');  
  6.    db.getRG(1).createNode('perftest-3',11820,'/opt/sequoiadb/database/cata/11820');  
  7.    db.getRG(1).getNode('perftest-2',11820).start();  
  8.    db.getRG(1).getNode('perftest-3',11820).start();  
  9.   
  10.    // group number is 8  
  11.    var port=11830;  
  12.    var hostid = 0;  
  13.    var diskno = 1;  
  14.    var diskids = [1,1,1,1];  
  15.    for(i=0;i<8;++i)  
  16.    {  
  17.       db.createRG('dg'+i);  
  18.       // 3 nodes of per group  
  19.       for (j=0;j<3;++j)  
  20.       {  
  21.          db.getRG('dg'+i).createNode('perftest-'+( hostid+1), port,'/data/disk' + diskids[hostid] + '/sequoiadb/database/data'+port);  
  22.          diskids[hostid] += 1;  
  23.          hostid += 1;  
  24.          if (hostid > 3)  
  25.          {  
  26.             hostid = 0;  
  27.          }  
  28.       }  
  29.       db.getRG('dg'+i).start();  
  30.       port += 10;  
  31.    }  
  32. }catch(e)  
  33. {  
  34.    throw e;  
  35. }  
创建分区集合的脚本如下(createcl.js): 

[js]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. try  
  2. {  
  3.    var db = new Sdb()  
  4.    db.dropCS('ycsb')  
  5. }catch(e)  
  6. {  
  7.    if (e != -34)  
  8.    {  
  9.       throw "drop cs failure" + e;  
  10.    }  
  11. }  
  12.   
  13. try  
  14. {  
  15.    db.createCS('ycsb')  
  16.    db.ycsb.createCL('usertable',{ShardingType:'hash',ShardingKey:{_id:1},EnsureShardingIndex:false})  
  17.    var snapshot8 = db.snapshot(8,{Name:'ycsb.usertable'}).toArray();  
  18.    var obj = eval ( "(" + snapshot8[0] + ")" );  
  19.    var srcgroup = obj["CataInfo"][0]["GroupName"];  
  20.    var partition = obj["Partition"];  
  21.   
  22.    var groupnames = new Array()  
  23.    var groups = db.list(7).toArray();  
  24.    for(i=0;i<groups.length;++i)  
  25.    {  
  26.       var group = eval("(" + groups[i] + ")");  
  27.       if (group["GroupName"] == "SYSCatalogGroup")  
  28.       {  
  29.          continue;  
  30.       }  
  31.       groupnames.push(group["GroupName"]);  
  32.    }  
  33.   
  34.    var remainderpart = partition % groupnames.length ;  
  35.    var part = (partition - remainderpart) / groupnames.length  
  36.    for(i=0;i<groupnames.length;++i)  
  37.    {  
  38.       if (groupnames[i] == srcgroup )  
  39.       {  
  40.          continue;  
  41.       }  
  42.       println("spliting from " + srcgroup + " to " + groupnames[i]+ "........");  
  43.       db.ycsb.usertable.split(srcgroup, groupnames[i], {Partition: (i*part)},{Partition:(i+1)*part});  
  44.       if (remainderpart > 1)  
  45.       {  
  46.          db.ycsb.usertable.split(srcgroup, groupnames[i], {Partition: endpart},{Partition: (endpart + 1)})  
  47.          endpart += 1;  
  48.          remainderpart -= 1;  
  49.       }  
  50.    }  
  51. }catch(e)  
  52. {  
  53.    throw e;  
  54. }  

3. HBase

HBase的数据分布情况如图11:

图11:HBase部署架构图

创始表语句使用:

create 'usertable', 'cf', {SPLITS => ['user1', 'user2', 'user3', 'user4', 'user5', 'user6', 'user7', 'user8', 'user9' ]}

5.4Cassandra

图12是一个Cassandra四节点集群。我们采用使用二十四块硬盘同时处理数据和提交日志。

 

图12:Cassandra部署架构图

与测试的其他数据库不同,Cassandra 在配置中使用环形拓扑,节点需要被明确地视为“种子”节点(这有助于它们加入到环中)。在配置时,必须指定哪些令牌将映射到哪些实例。

我们使用了 https://raw.github.com/riptano/ComboAMI/2.2/tokentoolv2.py提供的令牌生成工具来创建节点配置。 

[js]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. $ ./tokentoolv2.py 4   
  2. {   
  3. "0":{   
  4. "0":0,   
  5. "1":42535295865117307932921825928971026432,   
  6. "2":85070591730234615865843651857942052864,   
  7. "3":127605887595351923798765477786913079296   
  8. }   
  9. }   

Cassandra 的一致性级别可以调节。每次读取和写入都可以明确地说明该操作需要什么级别的数据库一致性。由于这是一个基准测试项目,因此我们使用了最弱和最快的一致性级别(ONE)来进行读取和写入。

对于所有数据库,我们使用的复制因子都是 2。其他主要设置为: 

内容
分区工具 RandomPartitioner
初始令牌空间 2^127 / 4
内存表空间 4GB
并发读取 48
并发写入 48
压缩 SnappyCompressor
提交日志同步 10000 ms
以下内容为 conf/cassandra.yaml 的设置: 

[js]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. cluster_name: 'Test'  
  2. initial_token: 0   
  3.   
  4. hinted_handoff_enabled: true  
  5. max_hint_window_in_ms: 3600000 # one hour  
  6. hinted_handoff_throttle_delay_in_ms: 1  
  7. authenticator: org.apache.cassandra.auth.AllowAllAuthenticator  
  8. authority: org.apache.cassandra.auth.AllowAllAuthority  
  9. partitioner: org.apache.cassandra.dht.RandomPartitioner  
  10. data_file_directories:  
  11.     - /data/disk1/cassandra-data  
  12.     - /data/disk2/cassandra-data  
  13.     - /data/disk3/cassandra-data  
  14.     - /data/disk4/cassandra-data  
  15.     - /data/disk5/cassandra-data  
  16.     - /data/disk6/cassandra-data  
  17.   
  18. commitlog_directory:   
  19.      /data/disk1/cassandra-log/,/data/disk2/cassandra-log/,/data/disk3/cassandra-log/,/data/disk4/cassandra-log/  
  20.      ,/data/disk5/cassandra-log/,/data/disk6/cassandra-log/  
  21.   
  22. saved_caches_directory: /data/disk1/apache-cassandra/saved_caches  
  23. commitlog_sync: periodic  
  24. commitlog_sync_period_in_ms: 10000  
  25.   
  26. seed_provider:  
  27.     - class_name: org.apache.cassandra.locator.SimpleSeedProvider  
  28.       parameter s:  
  29.           - seeds: "192.168.30.62,192.168.30.64,192.168.30.65,192.168.30.67"  
  30.   
  31.   
  32. flush_largest_memtables_at: 0.75  
  33.   
  34. reduce_cache_sizes_at: 0.85  
  35. reduce_cache_capacity_to: 0.6  
  36.   
  37. concurrent_reads: 48  
  38. concurrent_writes: 48  
  39.   
  40. memtable_flush_queue_size: 4  
  41.   
  42. sliced_buffer_size_in_kb: 64  
  43.   
  44. storage_port: 7000  
  45.   
  46. ssl_storage_port: 7001  
  47.   
  48. listen_address: 192.168.30.62   
  49.   
  50. rpc_address: 0.0.0.0   
  51. rpc_port: 9160  
  52.   
  53. rpc_keepalive: true  
  54.   
  55. rpc_server_type: sync  
  56. thrift_framed_transport_size_in_mb: 15  
  57.   
  58. thrift_max_message_length_in_mb: 16  
  59.   
  60. incremental_backups: false  
  61.   
  62. snapshot_before_compaction: false  
  63. column_index_size_in_kb: 64  
  64.   
  65. in_memory_compaction_limit_in_mb: 64  
  66.   
  67. multithreaded_compaction: false  
  68.   
  69. compaction_throughput_mb_per_sec: 16  
  70.   
  71. compaction_preheat_key_cache: true  
  72.   
  73. rpc_timeout_in_ms: 10000  
  74. endpoint_snitch: org.apache.cassandra.locator.SimpleSnitch  
  75.   
  76. dynamic_snitch_update_interval_in_ms: 100   
  77.   
  78. dynamic_snitch_reset_interval_in_ms: 600000  
  79. dynamic_snitch_badness_threshold: 0.1  
  80. request_scheduler: org.apache.cassandra.scheduler.NoScheduler  
  81.   
  82. index_interval: 128  
  83.   
  84. encryption_options:  
  85.     internode_encryption: none  
  86.     keystore: conf/.keystore  
  87.     keystore_password: cassandra  
  88.     truststore: conf/.truststore  
  89.     truststore_password: cassandra  
使用以下命令对数据库进行初始化:  

[js]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. CREATE KEYSPACE usertable   
  2. WITH placement_strategy = 'org.apache.cassandra.locator.SimpleStrategy' AND strategy_options = {replication_factor:2};   
  3. use usertable;   
  4. CREATE COLUMN FAMILY data WITH comparator = UTF8Type   
  5. AND key_validation_class = UTF8Type  
allowtransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?url=http%3A%2F%2Fwww.csdn.net%2Farticle%2F2014-09-16%2F2821707-benchmark-test-of-MongoDB-SequoiaDB-HBase-Cassandra%2F4&type=3&count=&appkey=&title=NoSQL%E9%80%9A%E8%BF%87%E5%BC%B1%E5%8C%96%E4%B8%80%E9%83%A8%E5%88%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%89%B9%E6%80%A7%EF%BC%88%E5%A6%82%E4%B8%80%E8%87%B4%E6%80%A7%E5%92%8C%E5%85%B3%E7%B3%BB%E6%A8%A1%E5%9E%8B%EF%BC%89%E6%9D%A5%E6%8F%90%E5%8D%87%E5%85%B6%E5%8F%AF%E6%89%A9%E5%B1%95%E6%80%A7%E5%8F%8A%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%A7%EF%BC%8C%E5%BC%A5%E8%A1%A5%E4%BA%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9C%A8%E5%BE%88%E5%A4%9A%E4%BA%92%E8%81%94%E7%BD%91%E7%B1%BB%E5%BA%94%E7%94%A8%E4%B8%AD%E7%9A%84%E4%B8%8D%E8%B6%B3%E3%80%82%E5%9B%A0%E6%AD%A4%EF%BC%8C%E4%B8%8D%E5%90%8C%E7%9A%84NoSQL%E6%9C%89%E7%9D%80%E4%B8%8D%E5%90%8C%E7%9A%84%E6%9D%80%E6%89%8B%E7%BA%A7%E5%BA%94%E7%94%A8%EF%BC%8C%E8%BF%99%E9%87%8C%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E5%9F%BA%E5%87%86%E6%B5%8B%E8%AF%95%E6%91%B8%E7%B4%A2%E3%80%82&pic=&ralateUid=&language=zh_cn&rnd=1411611053574" width="22" height="16"> 摘要:NoSQL通过弱化一部分关系型数据库特性(如一致性和关系模型)来提升其可扩展性及高可用性,弥补了关系型数据库在很多互联网类应用中的不足。因此,不同的NoSQL有着不同的杀手级应用,这里我们通过基准测试摸索。

附录B:YCSB调整

一、 驱动调整

1. MongoDB

  • 默认没有采用连接池的形式实现,调整为连接池形式
  • 默认不支持批量插入,增加支持批量插入
  • 默认不支持选择查询接口,增加支持选择查询接口
  • 默认不支持选择readpreference,增加支持选择readpreference
  • 为适应2.12.1版本的driver作了些调整

详细调整如下:

[js]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void init()  
  2.    {  
  3.     ...  
  4.       Properties props = getProperties();  
  5.       String url = props.getProperty("mongodb.url",  
  6.                                            "mongodb://localhost:27017");  
  7.       database = props.getProperty("mongodb.database""ycsb");  
  8.       String writeConcernType = props.getProperty("mongodb.writeConcern",  
  9.                                                         "safe").toLowerCase();  
  10.       //final String maxConnections = props.getProperty(  
  11.       //        "mongodb.maxconnections", "100");  
  12.       insertmode = props.getProperty("mongodb.insertmode""single");  
  13.       readpreference = props.getProperty("mongodb.readpreference",  
  14.                                                "primary");  
  15.       bulknumber=Integer.parseInt(props.getProperty("mongodb.bulknumber",   
  16.                                                           "5000"));  
  17.       final String find = props.getProperty("mongodb.usefindinterface",   
  18.                                                   "false");  
  19.     if (replWriteNum != 1){  
  20.                 writeConcern = new WriteConcern(replWriteNum);  
  21.             }  
  22.               
  23.             try {  
  24.                 // strip out prefix since Java driver doesn't currently support  
  25.                 // standard connection format URL yet  
  26.                 // <a href="http://www.mongodb.org/display/DOCS/Connections">http://www.mongodb.org/display/DOCS/Connections</a>  
  27.                /* if (url.startsWith("mongodb://")) { 
  28.                     url = url.substring(10); 
  29.                 }*/  
  30.                 // need to append db to url.  
  31.                 url += "/" + database;  
  32.                 System.out.println("new database url = " + url);  
  33.                 MongoClientURI uri = new MongoClientURI(url);  
  34.                 mongo = new MongoClient(uri);  
  35.                 mongo.setReadPreference(ReadPreference.valueOf(readpreference));  
  36.                 mongo.setWriteConcern(writeConcern);  
  37.                 System.out.println("mongo connection created with " + url);  
  38.             }  
  39.             catch (Exception e1) {  
  40.                 System.err  
  41.                         .println("Could not initialize MongoDB connection pool for Loader: "  
  42.                                 + e1.toString());  
  43.                 e1.printStackTrace();  
  44.                 return;  
  45.             }  
  46. }  
  47. public int insert(String table, String key,  
  48.             HashMap<String, ByteIterator> values) {  
  49.         com.mongodb.DB db = null;  
  50.         try {  
  51.             db = mongo.getDB(database);  
  52.             if (!outputclientflag){  
  53.                 CommandResult commandResult = db.command("buildInfo");  
  54.                 if (commandResult.containsField("tokumxVersion")){  
  55.                     System.out.println("tokumx");  
  56.                 }  
  57.                 else{  
  58.                     System.out.println("mongodb");  
  59.                 }  
  60.                 outputclientflag = true;  
  61.                 }  
  62.             db.requestStart();  
  63.   
  64.             DBCollection collection = db.getCollection(table);  
  65.             DBObject r = new BasicDBObject().append("_id", key);  
  66.             for (String k : values.keySet()) {  
  67.                 r.put(k, values.get(k).toArray());  
  68.             }  
  69.             //WriteResult res = null;  
  70.             if (insertmode.equals("bulk")){  
  71.                 objs.add(r);  
  72.            
  73.                 //bulkwrite.insert(r);  
  74.                 if (objs.size() == bulknumber){  
  75.                     //res =   
  76.                     collection.insert(objs);  
  77.                     objs.clear();  
  78.                     //return 0;  
  79.                 }  
  80.             }else{  
  81.                 //res =   
  82.                 collection.insert(r);  
  83.             }  
  84.               
  85.             //return res.getN() == replWriteNum ? 0:1;  
  86.             return 0;  
  87.         
  88.         }  
  89.         catch (Exception e) {  
  90.             e.printStackTrace();  
  91.             return 1;  
  92.         }  
  93.         finally {  
  94.             if (db != null) {  
  95.                 db.requestDone();  
  96.             }  
  97.         }  
  98.     }  
  99.   
  100. public int read(String table, String key, Set<String> fields,  
  101.             HashMap<String, ByteIterator> result) {  
  102.         com.mongodb.DB db = null;  
  103.         DBCursor cursor = null;  
  104.         try {  
  105.             db = mongo.getDB(database);  
  106.             db.requestStart();  
  107.             //getCollection(table);  
  108.             DBCollection collection = db.getCollection(table);  
  109.             DBObject q = new BasicDBObject().append("_id", key);  
  110.             DBObject fieldsToReturn = new BasicDBObject();  
  111.   
  112.             DBObject queryResult = null;  
  113.             //DBCursor cursor = null;  
  114.             if (fields != null) {  
  115.                 Iterator<String> iter = fields.iterator();  
  116.                 while (iter.hasNext()) {  
  117.                     fieldsToReturn.put(iter.next(), INCLUDE);  
  118.                 }  
  119.                 if (findone){  
  120.                     queryResult = collection.findOne(q, fieldsToReturn);  
  121.                 }  
  122.                 else{  
  123.                     cursor = collection.find(q,fieldsToReturn);  
  124.                 }   
  125.             }  
  126.             else {  
  127.                 if (findone){  
  128.                     queryResult = collection.findOne(q);  
  129.                 }  
  130.                 else{  
  131.                     cursor = collection.find(q).setReadPreference(ReadPreference.secondaryPreferred());  
  132.                 }  
  133.             }  
  134.               
  135.             if (cursor != null && cursor.hasNext()){  
  136.                 queryResult = cursor.next();  
  137.             }  
  138.   
  139.             if (queryResult != null) {  
  140.                 result.putAll(queryResult.toMap());  
  141.             }  
  142.             return queryResult != null ? 0 : 1;  
  143.         }  
  144.         catch (Exception e) {  
  145.             System.err.println(e.toString());  
  146.             return 1;  
  147.         }  
  148.         finally {  
  149.             if (db != null) {  
  150.                 db.requestDone();  
  151.             }  
  152.             if (cursor != null){  
  153.                 cursor.close();  
  154.             }      
  155.         }  
  156.     }  

2. HBase

  • 支持通过参数控制WriteBufferSize
  • 适应驱动做微调

详细如下:

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void init() throws DBException  
  2. {  
  3.         if ( (getProperties().getProperty("debug")!=null) &&  
  4.                 (getProperties().getProperty("debug").compareTo("true")==0) )  
  5.         {  
  6.             _debug=true;  
  7.         }  
  8.   
  9.         _columnFamily = getProperties().getProperty("columnfamily");  
  10.         if (_columnFamily == null)  
  11.         {  
  12.             System.err.println("Error, must specify a columnfamily for HBase table");  
  13.             throw new DBException("No columnfamily specified");  
  14.         }  
  15.         _columnFamilyBytes = Bytes.toBytes(_columnFamily);  
  16.           
  17.         clientbufsize = Integer.parseInt(getProperties().getProperty("clientbuffersize"));  
  18.  }  
  19.   
  20.   
  21. public void getHTable(String table) throws IOException  
  22.     {  
  23.         synchronized (tableLock) {  
  24.             _hTable = new HTable(config, table);  
  25.             //2 suggestions from <a href="http://ryantwopointoh.blogspot.com/2009/01/performance-of-hbase-importing.html">http://ryantwopointoh.blogspot.com/2009/01/performance-of-hbase-importing.html</a>  
  26.             _hTable.setAutoFlush(false);  
  27.             _hTable.setWriteBufferSize(clientbufsize*1024);  
  28.             //return hTable;  
  29.         }  
  30.   
  31.     }  

二、 统计数据收集

从原有的Measurements派生出ExcelMeasurementsExporter用于将生成的统计数据导出到excel文件中,ExcelMeasurementsExporter调用jxl.jar开源库实现。

 


统计数据由Overalloperresult、Overallresult,Periodresult这几个类存储,为了保存统计数据原来的Measurements,StatusThread都相应作了些调整。

三、 预热

增加如下xml配置文件

[xml]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <Test>  
  3. <load>  
  4.     <transaction name="bulkload_concurrent" />   
  5.     <!--transaction name="bulkload" /-->  
  6.     <transaction name="singleload_concurrent" />  
  7.     <!--transaction name="singleload" /-->          
  8. </load>  
  9. <run>    
  10.  <transaction name="readonly_concurrent" />   
  11.  <transaction name="readheavy_concurrent" />   
  12.  <transaction name="updateheavy_concurrent" />   
  13. <transaction name="insertheavy_concurrent" />   
  14.  <transaction name="readlastest_concurrent" />   
  15. </run>  
  16. </Test>  
我们增加了如下python脚本用于连续运行: 

[py]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. #!/usr/bin/python  
  2. #!/bin/env python  
  3.   
  4. import os  
  5. import sys  
  6. import subprocess  
  7. from xml.etree import ElementTree  
  8. import ycsb  
  9. from ycsb import (DATABASES,COMMANDS,BASE_URL,  
  10.                   get_ycsb_home, find_jars)   
  11.   
  12. def getloadtrans(workloadpath,root):  
  13.    load = []  
  14.    lst_node = root.find("load")  
  15.    for node in lst_node:  
  16.       load.append(workloadpath + node.attrib['name'])  
  17.    return load  
  18.   
  19. def getruntrans(workloadpath,root):  
  20.    run = []  
  21.    lst_node = root.find("run")  
  22.    for node in lst_node:  
  23.       run.append(workloadpath + node.attrib['name'])  
  24.    return run  
  25.   
  26. def ushelp():  
  27.    print "Usage: %s database  " % sys.argv[0]  
  28.    print "\nDatabases:"  
  29.    for db in sorted(DATABASES.keys()):  
  30.       print "    %s %s" % (db.ljust(13), BASE_URL + db.split("-")[0])  
  31.    sys.exit(1)  
  32.   
  33. def runscene(trans, cmd, db_classname, pervscene):  
  34.    curscene = ""  
  35.    for item in trans:  
  36.       curscene = os.path.basename(item)  
  37.       command = COMMANDS[cmd]["command"]  
  38.       options=["-s""-P", item]  
  39.       ycsb_command = ["java""-cp"":".join(find_jars(ycsb_home, database)), \  
  40.                        COMMANDS[cmd]["main"], "-db", db_classname] + options   
  41.       if command:  
  42.          ycsb_command.append(command)  
  43.          #print " ".join(ycsb_command)  
  44.       subprocess.call(ycsb_command)  
  45.       pervscene = curscene  
  46.    return pervscene  
  47.   
  48. if len(sys.argv) < 2:  
  49.     ushelp()  
  50. if sys.argv[1not in DATABASES:  
  51.     print "ERROR: Database '%s' not found" % sys.argv[1]  
  52.     ushelp()  
  53.   
  54. os.chdir('..')  
  55. conffile   = os.getcwd()+"/conf/workload.xml"  
  56. resultfile = os.getcwd()+"/result/report_output.xls"  
  57. resultdir  = os.getcwd()+"/result/"  
  58. workloadsdir = os.getcwd()+"/workloads/"  
  59.   
  60. if False == os.path.exists(conffile):  
  61.    print conffile + "not exist";  
  62.    sys.exit(1)  
  63.   
  64. root = ElementTree.parse(conffile)  
  65. loadtrans = getloadtrans(workloadsdir, root)  
  66. runtrans = getruntrans(workloadsdir, root)  
  67.   
  68. os.chdir('bin')  
  69. ycsb_home = get_ycsb_home()  
  70. database = sys.argv[1]  
  71. db_classname = DATABASES[database]  
  72.   
  73. runscene(loadtrans, "load", db_classname, pervscene)  
  74. runscene(runtrans, "run", db_classname, pervscene)  
  75.   
  76. import time  
  77. curtime=time.strftime("%Y-%m-%d_%H_%M_%S",time.localtime(time.time()))  
  78. newreportfile=resultdir + "report_" + curtime +".xls"  
  79. os.rename(resultfile, newreportfile)  

为尽量保证后续的查询、更新操作是基于前续的load操作,以保证缓存的高命中率。

四、 数据类型

本次测试的数据皆为字符串类型:

  • fieldcount=10
  • fieldlength=10
  • key字段由单词"user"后面加上64位的Fowler-Noll-Vo哈希值构成
  • key大小为23字节
  • 所有字段的值采用zipfian算法生成
allowtransparency="true" frameborder="0" scrolling="no" src="http://hits.sinajs.cn/A1/weiboshare.html?url=http%3A%2F%2Fwww.csdn.net%2Farticle%2F2014-09-16%2F2821707-benchmark-test-of-MongoDB-SequoiaDB-HBase-Cassandra%2F5&type=3&count=&appkey=&title=NoSQL%E9%80%9A%E8%BF%87%E5%BC%B1%E5%8C%96%E4%B8%80%E9%83%A8%E5%88%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E7%89%B9%E6%80%A7%EF%BC%88%E5%A6%82%E4%B8%80%E8%87%B4%E6%80%A7%E5%92%8C%E5%85%B3%E7%B3%BB%E6%A8%A1%E5%9E%8B%EF%BC%89%E6%9D%A5%E6%8F%90%E5%8D%87%E5%85%B6%E5%8F%AF%E6%89%A9%E5%B1%95%E6%80%A7%E5%8F%8A%E9%AB%98%E5%8F%AF%E7%94%A8%E6%80%A7%EF%BC%8C%E5%BC%A5%E8%A1%A5%E4%BA%86%E5%85%B3%E7%B3%BB%E5%9E%8B%E6%95%B0%E6%8D%AE%E5%BA%93%E5%9C%A8%E5%BE%88%E5%A4%9A%E4%BA%92%E8%81%94%E7%BD%91%E7%B1%BB%E5%BA%94%E7%94%A8%E4%B8%AD%E7%9A%84%E4%B8%8D%E8%B6%B3%E3%80%82%E5%9B%A0%E6%AD%A4%EF%BC%8C%E4%B8%8D%E5%90%8C%E7%9A%84NoSQL%E6%9C%89%E7%9D%80%E4%B8%8D%E5%90%8C%E7%9A%84%E6%9D%80%E6%89%8B%E7%BA%A7%E5%BA%94%E7%94%A8%EF%BC%8C%E8%BF%99%E9%87%8C%E6%88%91%E4%BB%AC%E9%80%9A%E8%BF%87%E5%9F%BA%E5%87%86%E6%B5%8B%E8%AF%95%E6%91%B8%E7%B4%A2%E3%80%82&pic=&ralateUid=&language=zh_cn&rnd=1411611082465" width="22" height="16"> 摘要:NoSQL通过弱化一部分关系型数据库特性(如一致性和关系模型)来提升其可扩展性及高可用性,弥补了关系型数据库在很多互联网类应用中的不足。因此,不同的NoSQL有着不同的杀手级应用,这里我们通过基准测试摸索。

附录C:SequoiaDB接口

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.yahoo.ycsb.db;  
  2. import com.yahoo.ycsb.ByteArrayByteIterator;  
  3. import com.yahoo.ycsb.ByteIterator;  
  4. import com.yahoo.ycsb.DB;  
  5. import com.yahoo.ycsb.DBException;  
  6.   
  7. import java.util.ArrayList;  
  8. import java.util.HashMap;  
  9. import java.util.Iterator;  
  10. import java.util.Map;  
  11. import java.util.Properties;  
  12. import java.util.Set;  
  13. import java.util.Vector;  
  14. import java.util.List;  
  15. import java.util.concurrent.atomic.AtomicInteger;  
  16.   
  17. import org.bson.BSONObject;  
  18. import org.bson.BasicBSONObject;  
  19. import org.bson.types.BasicBSONList;  
  20.   
  21. import com.sequoiadb.base.SequoiadbOption;  
  22. import com.sequoiadb.base.SequoiadbDatasource;  
  23. import com.sequoiadb.base.CollectionSpace;  
  24. import com.sequoiadb.base.DBCollection;  
  25. import com.sequoiadb.base.DBCursor;  
  26. import com.sequoiadb.base.Sequoiadb;  
  27.   
  28.   
  29. public class SequoiaDBClient extends DB {  
  30.   
  31.     /** Used to include a field in a response. */  
  32.     protected static final Integer INCLUDE = Integer.valueOf(1);  
  33.   
  34.     /** The key field name */  
  35.     //private static final String KEY_FILED = "key";  
  36.     private static final String KEY_FILED   = "_id";  
  37.     private static final String DEFAULT_INSERTMODE="single";  
  38.       
  39.     /** 
  40.      * Count the number of times initialized to teardown on the last 
  41.      * {@link #cleanup()}. 
  42.      */  
  43.     private static final AtomicInteger initCount = new AtomicInteger(0);  
  44.     private static int bulknum = 0;  
  45.   
  46.     /** Sequoiadb instance. */  
  47.     private static SequoiadbDatasource sdbpools = null;  
  48.     private Sequoiadb sdb = null;  
  49.     
  50.     /** CollectionSpace instance. */  
  51.     private CollectionSpace cs = null;  
  52.     private DBCollection cl       = null;  
  53.     private static String keyfield   = null;  
  54.     private static String insertmode = null;  
  55.     private List<BSONObject> objs    = new ArrayList<BSONObject>();   
  56.     //private int callnumber =0;  
  57.     private static String spacename = "ycsb";  
  58.       
  59.     //private DBCollection collection = null;  
  60.   
  61.     /** 
  62.      * Initialize any state for this DB. Called once per DB instance; there is 
  63.      * one DB instance per client thread. 
  64.      */  
  65.     public void init() throws DBException {  
  66.         initCount.incrementAndGet();  
  67.         synchronized (INCLUDE) {  
  68.             if (sdb != null) {  
  69.                 return;  
  70.             }  
  71.               
  72.             try{  
  73.                if (sdbpools != null){  
  74.                    sdb = sdbpools.getConnection();  
  75.                    cs = sdb.getCollectionSpace(spacename);  
  76.                    return;  
  77.                }  
  78.             }catch(Exception e){  
  79.                 e.printStackTrace();  
  80.                 return;  
  81.             }  
  82.               
  83.             // initialize sequoiadb driver  
  84.             Properties props = getProperties();  
  85.             String host = props.getProperty("sequoiadb.host""localhost");  
  86.             String port = props.getProperty("sequoiadb.port""11810");  
  87.             keyfield = props.getProperty("sequoiadb.keyfield""_id");  
  88.             int maxConnectionnum = Integer.parseInt(props.getProperty("sequoiadb.maxConnectionnum","100"));  
  89.             int maxidleconnnum = Integer.parseInt(props.getProperty("sequoiadb.maxConnectionnum","10"));  
  90.             int period = Integer.parseInt(props.getProperty("sequoiadb.maxConnectionnum","300"));  
  91.   
  92.             //String   
  93.             spacename = props.getProperty("sequoiadb.space", spacename);  
  94.             insertmode=props.getProperty("sequoiadb.insertmode", DEFAULT_INSERTMODE);  
  95.             bulknum = Integer.parseInt(props.getProperty("sequoiadb.bulknumber","5000"));  
  96.               
  97.             try {  
  98.                 SequoiadbOption sdbOption = new SequoiadbOption();  
  99.                 sdbOption.setMaxConnectionNum(maxConnectionnum);  
  100.                 sdbOption.setMaxIdeNum(maxidleconnnum);  
  101.                 sdbOption.setRecheckCyclePeriod(period*1000);  
  102.                   
  103.                 sdbpools = new SequoiadbDatasource(host+":"+port,"","",sdbOption);  
  104.                 // need to append db to url.  
  105.                 //sdb = new Sequoiadb(host, Integer.parseInt(port), "", "");  
  106.                 sdb = sdbpools.getConnection();  
  107.                 if (!sdb.isCollectionSpaceExist(spacename)) {  
  108.                     cs = sdb.createCollectionSpace(spacename);  
  109.                 } else {  
  110.                     cs = sdb.getCollectionSpace(spacename);  
  111.                 }  
  112.                 System.out.println("sequoiadb connection created with " + host  
  113.                         + ":" + port);  
  114.   
  115.             } catch (Exception e1) {  
  116.                 System.err  
  117.                         .println("Could not initialize Sequoiadb connection pool for Loader: "  
  118.                                 + e1.toString());  
  119.                 e1.printStackTrace();  
  120.                 throw new DBException(e1.toString());  
  121.             }  
  122.         }  
  123.     }  
  124.   
  125.     /** 
  126.      * Cleanup any state for this DB. Called once per DB instance; there is one 
  127.      * DB instance per client thread. 
  128.      */  
  129.     public void cleanup() throws DBException {  
  130.         initCount.decrementAndGet();  
  131.         try {  
  132.             if (0 != objs.size()){  
  133.                 cl.bulkInsert(objs, DBCollection.FLG_INSERT_CONTONDUP);  
  134.             }  
  135.             sdbpools.close(sdb);  
  136.         } catch (Exception e1) {  
  137.             System.err.println("Could not close Sequoiadb connection pool: "  
  138.                     + e1.toString());  
  139.             e1.printStackTrace();  
  140.             return;  
  141.         }  
  142.     }  
  143.     private List<String> getAllDataGroup(){  
  144.         // 获取数据组的数量  
  145.         List<String> groups = new ArrayList<String>();  
  146.         DBCursor cursor = sdb.getList(Sequoiadb.SDB_LIST_GROUPS, nullnullnull);  
  147.         while (cursor.hasNext()){  
  148.             BSONObject obj = cursor.getNext();  
  149.             String groupname = (String)obj.get("GroupName");  
  150.             if (!groupname.equals("SYSCatalogGroup")){  
  151.                 groups.add(groupname);  
  152.             }     
  153.         }  
  154.         return groups;  
  155.     }  
  156.       
  157.     private int getPartition(String spacename, String tablename){  
  158.         //获取源数据组  
  159.         BSONObject condition = new BasicBSONObject();  
  160.         condition.put("Name", spacename + "." + tablename);  
  161.         DBCursor cr = sdb.getSnapshot(Sequoiadb.SDB_SNAP_CATALOG, condition, nullnull);  
  162.         int Partition = 0;  
  163.         while(cr.hasNext()){  
  164.             BSONObject obj = cr.getNext();  
  165.             Partition = ((Integer)obj.get("Partition")).intValue();  
  166.         }  
  167.         return Partition;  
  168.     }  
  169.       
  170.     private String getSrcDataGroup(String spacename, String tablename){  
  171.         //获取源数据组  
  172.         BSONObject condition = new BasicBSONObject();  
  173.         condition.put("Name", spacename + "." + tablename);  
  174.         DBCursor cr = sdb.getSnapshot(Sequoiadb.SDB_SNAP_CATALOG, condition, nullnull);  
  175.         String srcgroup = "";  
  176.         while(cr.hasNext()){  
  177.             BSONObject obj = cr.getNext();  
  178.             BasicBSONList catainfo = (BasicBSONList)obj.get("CataInfo");  
  179.             srcgroup=(String)((BSONObject)catainfo.get(0)).get("GroupName");  
  180.         }  
  181.           
  182.         return srcgroup;  
  183.     }  
  184.       
  185.     private void splitCollection(DBCollection cl, String spacename, String tablename){  
  186.         // 获取数据组的数量  
  187.         List<String> groups = getAllDataGroup();  
  188.         int Partition = getPartition(spacename, tablename);  
  189.         String srcgroup = getSrcDataGroup(spacename, tablename);  
  190.           
  191.         int part = Partition / groups.size();  
  192.         int remainder = Partition % groups.size();  
  193.         int startpart = Partition - remainder;  
  194.         for (int i=0;i<groups.size();++i){  
  195.             //切分  
  196.             BSONObject start = new BasicBSONObject();  
  197.             start.put("Partition", i*part);  
  198.             BSONObject end = new BasicBSONObject();  
  199.             end.put("Partition", (i+1)*part);  
  200.             if (!groups.get(i).equals(srcgroup)){  
  201.                 cl.split(srcgroup, groups.get(i), start,end);  
  202.                   
  203.                 if (0 != remainder){  
  204.                     BSONObject remainderstart = new BasicBSONObject();  
  205.                     remainderstart.put("Partition", startpart);  
  206.                     BSONObject remainderend = new BasicBSONObject();  
  207.                     remainderend.put("Partition", startpart + 1);  
  208.                     cl.split(srcgroup, groups.get(i), remainderstart,remainderend);  
  209.                     --remainder;  
  210.                 }  
  211.             }  
  212.         }  
  213.     }  
  214.       
  215.     private void createCollection(String table) throws DBException {  
  216.         BSONObject options = new BasicBSONObject();  
  217.         BSONObject subobj = new BasicBSONObject();  
  218.         subobj.put(KEY_FILED, 1);  
  219.         options.put("ShardingKey", subobj);  
  220.         options.put("ShardingType""hash");  
  221.         options.put("EnsureShardingIndex"false);  
  222.           
  223.         cl = cs.createCollection(table, options);  
  224.         splitCollection(cl,spacename,table);  
  225.           
  226.         if (0 != keyfield.compareTo("_id")){  
  227.             cl.createIndex("index",  
  228.                            "{" + keyfield + ":1}"truetrue);  
  229.         }  
  230.     }  
  231.       
  232.     private DBCollection getCollection(String table){  
  233.         if (sdb == null){  
  234.             try{  
  235.                 sdb = sdbpools.getConnection();  
  236.             }catch(Exception e)  
  237.             {  
  238.                 e.printStackTrace();  
  239.                 return null;  
  240.             }  
  241.         }  
  242.           
  243.         if (cs == null){  
  244.             try{  
  245.                 cs = sdb.getCollectionSpace(spacename);  
  246.             }catch(Exception e)  
  247.             {  
  248.                 e.printStackTrace();  
  249.                 return null;  
  250.             }  
  251.         }  
  252.           
  253.         if (cl == null){  
  254.             try {  
  255.                 boolean bExist = cs.isCollectionExist(table);  
  256.                 if (!bExist) {  
  257.                     synchronized (INCLUDE) {  
  258.                         if (cs.isCollectionExist(table)) {  
  259.                             cl = cs.getCollection(table);  
  260.                         } else {  
  261.                             createCollection(table);  
  262.                         }  
  263.                     }  
  264.                 } else {  
  265.                     cl = cs.getCollection(table);  
  266.                 }  
  267.             }catch(Exception e)  
  268.             {  
  269.                 e.printStackTrace();  
  270.                 cl = null;  
  271.                 sdbpools.close(sdb);  
  272.                 sdb = null;  
  273.                 return getCollection(table);  
  274.             }  
  275.         }  
  276.         return cl;  
  277.     }  
  278.       
  279.     @Override  
  280.     public int read(String table, String key, Set<String> fields,  
  281.             HashMap<String, ByteIterator> result) {  
  282.         DBCursor cursor = null;  
  283.         DBCollection collection = null;  
  284.         try {  
  285.             collection = getCollection(table);  
  286.             if (collection == null) {  
  287.                 System.out.println("Failed to get collection " + table);  
  288.             }  
  289.   
  290.             BSONObject query = new BasicBSONObject().append(keyfield, key);  
  291.             BSONObject fieldsToReturn = null;  
  292.             if (fields != null) {  
  293.                 fieldsToReturn = new BasicBSONObject();  
  294.                 Iterator<String> iter = fields.iterator();  
  295.                 while (iter.hasNext()) {  
  296.                     fieldsToReturn.put(iter.next(), "");  
  297.                 }  
  298.             }  
  299.   
  300.             cursor = collection.query(query, fieldsToReturn, nullnull);  
  301.             if (cursor != null && cursor.hasNext()) {  
  302.                 HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>();  
  303.   
  304.                 fillMap(resultMap, cursor.getNext());  
  305.                 result.putAll(resultMap);  
  306.                 return 0;  
  307.             } else {  
  308.                 return 1;  
  309.             }  
  310.         } catch (Exception e) {  
  311.             System.err.println(e.toString());  
  312.             e.printStackTrace();  
  313.             return 1;  
  314.         } finally {  
  315.             if (cursor != null) {  
  316.                 cursor.close();  
  317.             }  
  318.         }  
  319.     }  
  320.   
  321.     /** 
  322.      * TODO - Finish 
  323.      *  
  324.      * @param resultMap 
  325.      * @param obj 
  326.      */  
  327.     @SuppressWarnings("unchecked")  
  328.     protected void fillMap(HashMap<String, ByteIterator> resultMap,  
  329.                            BSONObject obj) {  
  330.         Map<String, Object> objMap = obj.toMap();  
  331.         for (Map.Entry<String, Object> entry : objMap.entrySet()) {  
  332.             if (entry.getValue() instanceof byte[]) {  
  333.                 resultMap.put(entry.getKey(), new ByteArrayByteIterator(  
  334.                         (byte[]) entry.getValue()));  
  335.             }  
  336.         }  
  337.     }  
  338.   
  339.     @Override  
  340.     public int scan(String table, String startkey, int recordcount,  
  341.             Set<String> fields, Vector<HashMap<String, ByteIterator>> result) {  
  342.         DBCursor cursor = null;  
  343.         try {  
  344.             DBCollection collection = getCollection(table);  
  345.               
  346.             BSONObject scanRange = new BasicBSONObject().append("$gte",  
  347.                                          startkey);  
  348.             BSONObject query = new BasicBSONObject().append(keyfield,  
  349.                                      scanRange);  
  350.             BSONObject fieldsToReturn = null;  
  351.             if (fields != null) {  
  352.                 fieldsToReturn = new BasicBSONObject();  
  353.                 Iterator<String> iter = fields.iterator();  
  354.                 while (iter.hasNext()) {  
  355.                     fieldsToReturn.put(iter.next(), "");  
  356.                 }  
  357.             }  
  358.   
  359.             cursor = collection.query(query, fieldsToReturn, nullnull0,  
  360.                                       recordcount);  
  361.             while (cursor.hasNext()) {  
  362.                 // toMap() returns a Map, but result.add() expects a  
  363.                 // Map<String,String>. Hence, the suppress warnings.  
  364.                 HashMap<String, ByteIterator> resultMap = new HashMap<String, ByteIterator>();  
  365.                 BSONObject obj = cursor.getNext();  
  366.                 fillMap(resultMap, obj);  
  367.                 result.add(resultMap);  
  368.             }  
  369.             return 0;  
  370.         } catch (Exception e) {  
  371.             System.err.println(e.toString());  
  372.             e.printStackTrace();  
  373.             return 1;  
  374.         } finally {  
  375.             if (cursor != null) {  
  376.                 cursor.close();  
  377.             }  
  378.         }  
  379.     }  
  380.   
  381.     @Override  
  382.     public int update(String table, String key,  
  383.             HashMap<String, ByteIterator> values) {  
  384.         try {  
  385.             DBCollection collection = getCollection(table);  
  386.             if (collection == null) {  
  387.                 System.out.println("Failed to get collection " + table);  
  388.                 return -1;  
  389.             }  
  390.               
  391.             BSONObject query = new BasicBSONObject().append(keyfield, key);  
  392.             BSONObject update = new BasicBSONObject();  
  393.             BSONObject fieldsToSet = new BasicBSONObject();  
  394.               
  395.             Iterator<String> keys = values.keySet().iterator();  
  396.             while (keys.hasNext()) {  
  397.                 String tmpKey = keys.next();  
  398.                 fieldsToSet.put(tmpKey, values.get(tmpKey).toArray());  
  399.             }  
  400.               
  401.             update.put("$set", fieldsToSet);  
  402.             collection.update(query, update, null);  
  403.             return 0;  
  404.         } catch (Exception e) {  
  405.             System.err.println(e.toString());  
  406.             e.printStackTrace();  
  407.             return 1;  
  408.         }  
  409.     }  
  410.   
  411.     @Override  
  412.     public int insert(String table, String key,  
  413.             HashMap<String, ByteIterator> values) {  
  414.         try {  
  415.             DBCollection collection = getCollection(table);  
  416.             BSONObject record = new BasicBSONObject().append(keyfield, key);  
  417.             for (String k : values.keySet()) {  
  418.                 record.put(k, values.get(k).toArray());  
  419.             }  
  420.               
  421.             if (insertmode.equals(DEFAULT_INSERTMODE)){  
  422.                 collection.insert(record);  
  423.             }  
  424.             else{  
  425.                 if (objs.size() != bulknum){  
  426.                     objs.add(record);  
  427.                 }  
  428.                   
  429.                 if (objs.size() ==  bulknum){  
  430.                     collection.bulkInsert(objs,DBCollection.FLG_INSERT_CONTONDUP);  
  431.                     objs.clear();  
  432.                 }  
  433.             }  
  434.             return 0;  
  435.         } catch (Exception e) {  
  436.             System.err.println(e.toString());  
  437.             e.printStackTrace();  
  438.             return 1;  
  439.         }  
  440.     }  
  441.   
  442.     @Override  
  443.     public int delete(String table, String key) {  
  444.         try {  
  445.             DBCollection collection = getCollection(table);  
  446.             BSONObject record = new BasicBSONObject().append(keyfield, key);  
  447.             collection.delete(record);  
  448.             return 0;  
  449.         } catch (Exception e) {  
  450.             System.err.println(e.toString());  
  451.             e.printStackTrace();  
  452.             return 1;  
  453.         }  
  454.     }  
  455.       
  456.     public static void main(String[] args){  
  457.           
  458.         Properties props = new Properties();  
  459.         props.setProperty("sequoiadb.host""192.168.30.63");  
  460.         props.setProperty("sequoiadb.port""11810");  
  461.         props.setProperty("sequoiadb.space""test");  
  462.   
  463.         SequoiaDBClient client = new SequoiaDBClient();  
  464.         client.setProperties(props);  
  465.           
  466.         try{  
  467.             client.init();  
  468.             client.getCollection("usertable");  
  469.         }catch(DBException e){  
  470.             e.printStackTrace();  
  471.         }  
  472.     }  
  473. }  

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值