cassandra学习笔记三

这里我们开始使用JAVA来操作cassandra数据库,而不仅限于客户端操作。关于客户端cassandra-clinodetool的操作,在命令行使用help命令可以获取很多帮助。

我使用的是thrift来操作数据库,这是一种较低级的方法,它直接使用最基本的API。尽管有更高级的方式来操作,但熟悉API依然是必须的,因此我们先使用thrift

首先要在JAVA里导入包,在MyEclipse里右键工程名,选择properties,进入JavaBuildPath->Libraries,选择AddExternalJars,导入:

Apache-cassandra-1.0.8.jar

Apache-cassandra-thrift-1.0.8.jar

libthrift-0.6.jar

log4j-1.2.16.jar

slf4j-api-1.6.1.jar

slf4j-log4j12-1.6.1.jar

这些JAR包都在canssandra目录下的lib文件夹内。

下面是测试代码:

package cassandra;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.List;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
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.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.thrift.TBinaryProtocol;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class TestClient
{
	public static void main(String[] args)
		throws TException, InvalidRequestException, 		
		UnavailableException, UnsupportedEncodingException,
		NotFoundException, TimedOutException
	{
		//包装好的socket
		TTransport tr = new TFramedTransport(new TSocket("127.0.0.1",9160));
		TProtocol proto = new TBinaryProtocol(tr);
		Cassandra.Client client = new Cassandra.Client(proto);
		tr.open();
		
		if(!tr.isOpen())
		{
			System.out.println("failed to connect server!");
			return;
		}
		
		long temp = System.currentTimeMillis();
		
		client.set_keyspace("DEMO");//使用DEMO keyspace
		ColumnParent parent = new ColumnParent("Student");//column family
		
		/*
		 * 这里我们插入100万条数据到Student内
		 * 每条数据包括id和name
		 */
		String key_user_id = "a";
		for(int i = 0;i < 1000000;i++)
		{
			String k = key_user_id + i;//key
			long timestamp = System.currentTimeMillis();//时间戳
			
			Column idColumn = new Column(toByteBuffer("id"));//column name
			idColumn.setValue(toByteBuffer(i + ""));//column value
			idColumn.setTimestamp(timestamp);
			client.insert(
				toByteBuffer(k), 
				parent, 
				idColumn, 
				ConsistencyLevel.ONE);
			
			Column nameColumn = new Column(toByteBuffer("name"));
			nameColumn.setValue(toByteBuffer("student" + i));
			nameColumn.setTimestamp(timestamp);
			client.insert(
				toByteBuffer(k), 
				parent, 
				nameColumn, 
				ConsistencyLevel.ONE);
		}
	
		/*
		 * 读取某条数据的单个字段
		 */
		ColumnPath path = new ColumnPath("Student");//设置读取Student的数据
		path.setColumn(toByteBuffer("id"));	//读取id	
		String key3 = "a1";//读取key为a1的那条记录
		System.out.println(toString(client.get(toByteBuffer(key3), path, ConsistencyLevel.ONE).column.value));
		
		/*
		 * 读取整条数据
		 */
		SlicePredicate predicate = new SlicePredicate();
		SliceRange sliceRange = new SliceRange(toByteBuffer(""), toByteBuffer(""), false, 10);
		predicate.setSlice_range(sliceRange);
		List<ColumnOrSuperColumn> results = 
			client.get_slice(toByteBuffer(key3), parent, predicate, ConsistencyLevel.ONE);
		
		for (ColumnOrSuperColumn result : results)
		{
			Column column = result.column;
			System.out.println(toString(column.name) + " -> " + toString(column.value));
		}
		
		long temp2 = System.currentTimeMillis();
		System.out.println("time: " + (temp2 - temp) + " ms");//输出耗费时间
		
		tr.close();
	}
	
	/*
	 * 将String转换为bytebuffer,以便插入cassandra
	 */
	public static ByteBuffer toByteBuffer(String value) 
		throws UnsupportedEncodingException
	{
		return ByteBuffer.wrap(value.getBytes("UTF-8"));
	}
    
	/*
	 * 将bytebuffer转换为String
	 */
	public static String toString(ByteBuffer buffer) 
		throws UnsupportedEncodingException
	{
		byte[] bytes = new byte[buffer.remaining()];
	    buffer.get(bytes);
	    return new String(bytes, "UTF-8");
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值