深入显出cassandra 2 第一个可以运行的例子

深入浅出cassandra 2 第一个可以运行的例子

深入浅出cassandra 2 第一个可以运行的例子

在上一篇文章中,我们成功的建立了一个可以cassandra的实例,同时也让它成功的运行起来,下面的工作就是让我们来简单的操作一下这个
号称分布式的号称第二代的数据库系统。

 

本文主要关注两个部分,
1. 怎么写一个最简单cassandra的sample
2. 怎么去分析这个最简单的sample背后隐含的含义



步骤一:
1. 首先我们创建一个工程,然后将cassandra/lib目录下的包,导入到我们的工程中。

2. 非常重要的一点

 

编程接口Thrift的配置 
使用下面的命令,获取Thrift的压缩包
wget -O thrift.tgz http://gitweb.thrift-rpc.org/?p=thrift.git;a=snapshot;h=HEAD;sf=tgz
如果使用Java语言,可以在解压Thrift后,到安装目录下的/lib/java目录,使用ant编译得到libthrift.jar

 

注意:
编译Java的jar时,需要用到ant,版本需要在1.7.1及以上,不然在编译时提示"not support nested 'typedef' element"的异常

 

而且在ant操作时,不能仅仅只拿出lib/java这个文件,须要在整个thrift这个大工程下ant       

 

步骤二:
创建一个类,内容如下:
Java代码 :
[c-sharp] view plaincopy
  1. package com.taobao.zhujiadun.basic;  
  2. import org.apache.cassandra.thrift.Cassandra;  
  3. import org.apache.cassandra.thrift.Column;  
  4. import org.apache.cassandra.thrift.ColumnPath;  
  5. import org.apache.cassandra.thrift.ConsistencyLevel;  
  6. import org.apache.cassandra.thrift.InvalidRequestException;  
  7. import org.apache.cassandra.thrift.NotFoundException;  
  8. import org.apache.cassandra.thrift.TimedOutException;  
  9. import org.apache.cassandra.thrift.UnavailableException;  
  10. import org.apache.thrift.TException;  
  11. import org.apache.thrift.protocol.TBinaryProtocol;  
  12. import org.apache.thrift.transport.TSocket;  
  13. import org.apache.thrift.transport.TTransport;  
  14. import org.apache.thrift.transport.TTransportException;  
  15.  public class SampleOne {    
  16.      static Cassandra.Client cassandraClient;    
  17.      static TTransport socket;  
  18.      
  19.      
  20.      private static void init() throws TTransportException {    
  21. //         String server = "192.168.1.129";    
  22.          String server = "localhost";  
  23.          int port = 9160;    
  24.      
  25.          /* 首先指定cassandra server的地址 */    
  26.          socket = new TSocket(server, port);    
  27.          System.out.println(" connected to " + server + ":" + port + ".");    
  28.      
  29.      
  30.          /* 指定通信协议为二进制流协议 */    
  31.          TBinaryProtocol binaryProtocol = new TBinaryProtocol(socket, falsefalse);    
  32.          cassandraClient = new Cassandra.Client(binaryProtocol);    
  33.      
  34.      
  35.          /* 建立通信连接 */    
  36.          socket.open();    
  37.      }    
  38.      
  39.      
  40.      public static void main(String[] args) throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException {    
  41.          /* 初始化连接 */    
  42.          init();    
  43.      
  44.      
  45.          /* 选择需要操作的Keyspaces, 可以理解成数据库的表 */    
  46.          String keyspace= "Keyspace1";    
  47.          String row = "employee";    
  48.      
  49.          /* 创建一个Table Name */    
  50.          String tableName = "Standard2";  
  51.            
  52.          /* 插入一条记录 */  
  53.          insertOrUpdate(keyspace,tableName,row,"name","happy birthday!",System.currentTimeMillis());  
  54.          /* 删除一条记录 */  
  55.          //delete(keyspace,tableName,row,"name",System.currentTimeMillis());  
  56.          /* 获取一条记录 (由于插入和删除是同一条记录,有可能会检索不到哦!请大家主意!*/  
  57.          Column column = getByColumn(keyspace,tableName,row,"name", System.currentTimeMillis());  
  58.          System.out.println("read row " + row);    
  59.          System.out.println("column name " + ":" + new String(column.name));    
  60.          System.out.println("column value" + ":" + new String(column.value));    
  61.          System.out.println("column timestamp" + ":" + (column.timestamp));    
  62.            
  63.          close();  
  64.      }  
  65.        
  66.      /** 
  67.       * 插入记录 
  68.       */  
  69.      public static void insertOrUpdate(String tableSpace,String tableName, String rowParam,String ColumnName,String ColumnValue,long timeStamp)    
  70.         throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException{  
  71.          /* 选择需要操作的Keyspaces, 存放数据表所在的空间位置 */    
  72.          String keyspace= tableSpace;  
  73.          /* 数据所在的行标 */  
  74.          String row = rowParam;    
  75.      
  76.          /* 创建一个column path */    
  77.          ColumnPath col = new ColumnPath(tableName);    
  78.          col.setColumn(ColumnName.getBytes());   
  79.            
  80.          /* 执行插入操作,指定keysapce, row, col, 和数据内容, 后面两个参数一个是timestamp, 另外一个是consistency_level  
  81.           * timestamp是用来做数据一致性保证的, 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo  
  82.           */    
  83.         cassandraClient.insert(keyspace, row, col,"i don't know".getBytes(), System.currentTimeMillis(), ConsistencyLevel.ONE);  
  84.      }  
  85.        
  86.      /** 
  87.       * 删除记录 
  88.       */  
  89.      public static void delete(String tableSpace,String tableName, String rowParam,String ColumnName,long timeStamp)   
  90.         throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException{  
  91.          /* 选择需要操作的Keyspaces, 存放数据表所在的空间位置 */    
  92.          String keyspace= tableSpace;  
  93.          /* 数据所在的行标 */  
  94.          String row = rowParam;    
  95.      
  96.          /* 创建一个column path */    
  97.          ColumnPath col = new ColumnPath(tableName);    
  98.          col.setColumn(ColumnName.getBytes());   
  99.            
  100.          /* 执行删除操作,指定keysapce, row, col, 后面两个参数一个是timestamp, 另外一个是consistency_level  
  101.           * timestamp是用来做数据一致性保证的, 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo  
  102.           */    
  103.         cassandraClient.remove(keyspace, row, col, System.currentTimeMillis(), ConsistencyLevel.ONE);  
  104.      }  
  105.        
  106.      /** 
  107.       * 获取数据 
  108.       */  
  109.      public static Column getByColumn(String tableSpace,String tableName, String rowParam,String ColumnName,long timeStamp)   
  110.     throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException{  
  111.       /* 选择需要操作的Keyspaces, 存放数据表所在的空间位置 */    
  112.       String keyspace= tableSpace;   
  113.       /* 数据所在的行标 */  
  114.       String row = rowParam;    
  115.       /* 创建一个column path */    
  116.       ColumnPath col = new ColumnPath(tableName);    
  117.       col.setColumn(ColumnName.getBytes());   
  118.         
  119.       /* 执行查询操作,指定keysapce, row, col, timestamp  
  120.        * timestamp是用来做数据一致性保证的, 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo  
  121.        */    
  122.       Column column = cassandraClient.get(keyspace, row, col, ConsistencyLevel.ONE).column;    
  123.       return column;  
  124.      }  
  125.        
  126.        
  127.      /** 
  128.       * 关闭当前的远程访问连接 
  129.       */  
  130.      public static void close() {  
  131.          socket.close();  
  132.     }  
  133.  }    

为了比较好的理解这些名词解释,我们先看看cassandra的数据模型: 

深入显出cassandra 2 第一个可以运行的例子

 

Cassandra 的数据模型的基本概念: 
keyspace: 
用于存放 ColumnFamily 的容器,相当于关系数据库中的 Schema 或 database, 
ColumnFamily : 
用于存放 Column 的容器,类似关系数据库中的 table 的概念。 

SuperColumn : 
它是一个特列殊的 Column, 它的 Value 值可以包函多个 Column 

[c-sharp] view plaincopy
  1. {   // 这是一个SuperColumn  
  2.     name: "李明杰",  
  3.    // 包含一系列的Columns  
  4.    value: {  
  5.     street: {name: "street", value: "1234 x street", timestamp: 123456789},  
  6.     city: {name: "city", value: "san francisco", timestamp: 123456789},  
  7.     zip: {name: "zip", value: "94107", timestamp: 123456789},  
  8.    }  
  9. }  
Columns: 
Cassandra 的最基本单位。由 name , value , timestamp 组成 
[c-sharp] view plaincopy
  1. {  // 这是一个column  
  2.   name: "李明杰",  
  3.   value: "mydream.limj@gmali.com",  
  4.   timestamp: 123456789  
  5. }   
cassandra的数据模型主要就是由上述几种模型构建而成的,很简单吧,的确是这样,最大的好处就是读写数据的API非常简单. 
1. 首先我们来说说keyspace是个什么玩意
打开storage-conf.xml,找到<Keyspaces>这个xml节点,我们可以看到一段对keyspace的说明, 如下:
ColumnFamily在cassandra中概念最接近关系型数据库中的表。而keyspace则是一堆ColumnFamily的集合。如果说ColumnFamily是表,那么我们可以将keyspace称之库

我们来看一段简单的配置。

 

Java代码 
[c-sharp] view plaincopy
  1. <Keyspaces>  
  2.     <Keyspace Name="Keyspace1">  
  3.       <ColumnFamily CompareWith="BytesType" Name="Standard1"/>  
  4.       <ColumnFamily CompareWith="UTF8Type" Name="Standard2"/>  
  5.       <ColumnFamily CompareWith="TimeUUIDType" Name="StandardByUUID1"/>  
  6.       <ColumnFamily ColumnType="Super"  
  7.                     CompareWith="UTF8Type"  
  8.                     CompareSubcolumnsWith="UTF8Type"  
  9.                     Name="Super1"  
  10.                     Comment="A column family with supercolumns, whose column and subcolumn names are UTF8 strings"/>  
  11.     </Keyspace>  
  12.     <Keyspace Name="ahuaxuan">  
  13.       <ColumnFamily CompareWith="BytesType" Name="test1"/>  
  14.       <ColumnFamily CompareWith="UTF8Type" Name="test2"/>  
  15.       <ColumnFamily ColumnType="Super"  
  16.                     CompareWith="UTF8Type"  
  17.                     CompareSubcolumnsWith="UTF8Type"  
  18.                     Name="Super1"  
  19.                     Comment="A column family with supercolumns, whose column and subcolumn names are UTF8 strings"/>  
  20.     </Keyspace>  
  21.   </Keyspaces>  
 

  

这段配置表示我们的cassandra中有多个keyspace, 而每个keyspace下又有多个ColumnFamil