`
4everwinter
  • 浏览: 1263 次
  • 性别: Icon_minigender_1
  • 来自: 天津
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

Hello World of Cassandra 0.7 in Eclipse

阅读更多

前几天弄了0.6.8想凑合着先用,后来发现没有能够方便添加keyspace和col family的特性,就转向0.7了

 

run cassandra in eclipse的问题照着官方文档走就应该没有问题的...

 

http://wiki.apache.org/cassandra/RunningCassandraInEclipse

http://sunmoonone.iteye.com/blog/644022

 

 

关于CLI的使用,先手动添加一个keyspace - keysp1,CF是student

http://wiki.apache.org/cassandra/CassandraCli

 

代码上是拿原来的sample改的,有些注释过来了

package atest;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import common.test.Translater;


 public class SampleOne { 
     static Cassandra.Client cassandraClient; 
     static TTransport socket;
  
  
     private static void init(String keySpace) throws InvalidRequestException, TException { 
//       String server = "192.168.1.129"; 
         String server = "localhost";
         int port = 9160; 
  
         /* 首先指定cassandra server的地址 */ 
         socket = new TSocket(server, port); 
         System.out.println(" connected to " + server + ":" + port + "."); 
  
         TFramedTransport transport = new TFramedTransport(socket);
        
         /* 指定通信协议为二进制流协议 */ 
         TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport); 
         cassandraClient = new Cassandra.Client(binaryProtocol); 
  
         /* 建立通信连接 */ 
         socket.open();
         cassandraClient.set_keyspace(keySpace);
     } 
  
  
     public static void main(String[] args) throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException { 
         /* 选择需要操作的Keyspaces, 可以理解成数据库的表 */ 
         String keyspace= "keysp1";
        
         /* 初始化连接 */ 
         init(keyspace); 
        
         String row = "employee";
  
         /* 创建一个Table Name */ 
         String tableName = "student";
        
         /* 插入一条记录 */
         insertOrUpdate(tableName,row,"name","happy birthday!",System.currentTimeMillis());
         /* 删除一条记录 */
         //delete(keyspace,tableName,row,"name",System.currentTimeMillis());
         /* 获取一条记录 (由于插入和删除是同一条记录,有可能会检索不到哦!请大家主意!*/
         Column column = getByColumn(tableName,row,"name", System.currentTimeMillis());
        
         System.out.println("read row " + row); 
         System.out.println("column name " + ":" + new String(column.getName())); 
         System.out.println("column value" + ":" + new String(column.getValue())); 
         System.out.println("column timestamp" + ":" + (column.timestamp)); 
        
         close();
     }
    
     /**
      * 插入记录
      */
     public static void insertOrUpdate(String tableName, String rowParam,String ColumnName,String ColumnValue,long timeStamp) 
         throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException{
         /* 数据所在的行标 */
         String row = rowParam;
  
         /* 创建一个column path */ 
         ColumnParent parent = new ColumnParent(tableName); 
         Column col = new Column();
         col.setName(ColumnName.getBytes());
         col.setValue(ColumnValue.getBytes());
        
         /* 执行插入操作,指定keysapce, row, col, 和数据内容, 后面两个参数一个是timestamp, 另外一个是consistency_level
          * timestamp是用来做数据一致性保证的, 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo
          */ 
        cassandraClient.insert(Translater.toByteBuffer(row), parent, col, ConsistencyLevel.ONE);
     }
    
     /**
      * 删除记录
      */
     public static void delete(String tableName, String rowParam,String ColumnName,long timeStamp)
         throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException{
         /* 选择需要操作的Keyspaces, 存放数据表所在的空间位置 */ 
         /* 数据所在的行标 */
         String row = rowParam; 
  
         /* 创建一个column path */ 
         ColumnPath col = new ColumnPath(tableName); 
         col.setColumn(ColumnName.getBytes());
        
         /* 执行删除操作,指定keysapce, row, col, 后面两个参数一个是timestamp, 另外一个是consistency_level
          * timestamp是用来做数据一致性保证的, 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo
          */ 
        cassandraClient.remove(Translater.toByteBuffer(row), col, System.currentTimeMillis(), ConsistencyLevel.ONE);
     }
    
     /**
      * 获取数据
      */
     public static Column getByColumn(String tableName, String rowParam,String ColumnName,long timeStamp)
      throws TException, TimedOutException, InvalidRequestException, UnavailableException, NotFoundException{

      /* 创建一个column path */ 
      ColumnPath col = new ColumnPath(tableName); 
      col.setColumn(ColumnName.getBytes());
     
      /* 执行查询操作,指定keysapce, row, col, timestamp
       * timestamp是用来做数据一致性保证的, 而consistency_level是用来控制数据分布的策略,前者的理论依据是bigtable, 后者的理论依据是dynamo
       */ 
      Column column = cassandraClient.get(Translater.toByteBuffer(rowParam), col, ConsistencyLevel.ONE).column; 
      return column;
     }
    
    
     /**
      *    关闭当前的远程访问连接
      */
     public static void close() {
         socket.close();
    }
 } 

 

 Translater的代码

package common.test;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;

public class Translater {

	public static Charset charset = Charset.forName("UTF-8");
	public static CharsetEncoder encoder = charset.newEncoder();
	public static CharsetDecoder decoder = charset.newDecoder();

	public static ByteBuffer toByteBuffer(String msg) {
		try {
			return encoder.encode(CharBuffer.wrap(msg));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static String toString(ByteBuffer buffer) {
		String data = "";
		try {
			int old_position = buffer.position();
			data = decoder.decode(buffer).toString();
			// reset buffer's position to its original so it is not altered:
			buffer.position(old_position);
		} catch (Exception e) {
			e.printStackTrace();
			return "";
		}
		return data;
	}
}

 

其实关于连接的几行代码还是不准确,自己太菜了,继续上链接

http://rucbing.iteye.com/blog/789229

 

分享到:
评论

相关推荐

    cassandra 2.0.8 source code for eclipse (Win32) part1

    cassandra 2.0.8 source code for eclipse (Win32) part1 JDK 1.7.0_60 (location Default) Cassandra 2.0.8

    MariaDB Cassandra interoperability Cassandra Storage Engine in MariaDB

    标题与描述均提到了“MariaDB与Cassandra的互操作性”,这主要指的是MariaDB中的Cassandra存储引擎(Cassandra Storage Engine)。这是一个重要的知识点,它实现了MariaDB与Cassandra数据库之间的桥梁,允许用户在...

    cassandra 2.0.8 source code for eclipse (Linux 32bit)

    cassandra 2.0.8 source code for eclipse (Linux 32bit) /usr/java /usr/apache-cassandra-2.0.8

    Cassandra Design Patterns

    This practical guide will help you understand the strengths and weaknesses of Cassandra and teach you to how to identify business and technical use cases that Cassandra solves.You will also learn how ...

    Cassandra

    The rising popularity of Apache Cassandra rests on its ability to handle very large data sets that include hundreds of terabytes -- and that's why this distributed database has been chosen by ...

    Cassandra High Availability(PACKT,2014)

    Apache Cassandra is a massively scalable, peer-to-peer database designed for 100 percent uptime, with deployments in the tens of thousands of nodes supporting petabytes of data. This book offers ...

    NoSQL Web Development with Apache Cassandra(2015)

    Apache Cassandra is the most commonly used NoSQL database written in Java and is renowned in the industry as the only NoSQL solution that can accommodate the complex requirements of today’s modern ...

    Learning Apache Cassandra - Second Edition

    The book starts by explaining the new features implemented in Cassandra 3.x and get you set up with Cassandra. Then you'll walk through data modeling in Cassandra and the rich feature set available to...

    CASSANDRA分布式模型与源代码分析文茂V0.7 - CASSANDRA-SHAWN.doc

    Cassandra 是一个开源的分布式数据库管理系统,源自Facebook,后来发展为Apache项目。它结合了Dynamo的Key/Value存储和Bigtable的列族数据模型,适用于处理大规模数据。Cassandra的特点包括: 1. 活动灵活的Schema...

    cassandra-benchmark

    This technical report presents the results of a benchmark test conducted by Locomatix, Inc., on Apache’s Cassandra open-source distributed database management system (DBMS), utilizing the Violin ...

    cassandra入门项目源代码

    【标题】:“Cassandra入门项目源代码”是一个针对初学者的教程项目,旨在帮助开发者了解如何在Eclipse环境中使用Spring Data框架与EasyRest风格来操作Cassandra数据库和Lucene搜索引擎。这个项目提供了一整套实践性...

Global site tag (gtag.js) - Google Analytics