2011年9月30日金曜日

Hectorを使ったCassandraへのアクセス

Cassandraの高度クライアントであるHectorを使用したアクセス方法。
まずは、チュートリアルレベルのものを試してみた。
ちなみに、Cassandraは0.8.4を使用している。

今回はCQLではなく昔からあったアクセス方法みたいなやり方。
ソース貼付けてさぼります。


package com.zomu.t;

import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.OrderedRows;
import me.prettyprint.hector.api.beans.Row;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.factory.HFactory;
import me.prettyprint.hector.api.mutation.Mutator;
import me.prettyprint.hector.api.query.QueryResult;
import me.prettyprint.hector.api.query.RangeSlicesQuery;

public class AccessTest {

	private static StringSerializer stringSerializer = StringSerializer.get();

	public static void main(String[] args) {

		Cluster cluster = HFactory.getOrCreateCluster("TestCluster",
				"localhost:9160");

		Keyspace keyspaceOperator = HFactory.createKeyspace("KeySpace", cluster);

		try {
			Mutator mutator = HFactory.createMutator(keyspaceOperator,
					stringSerializer);

			RangeSlicesQuery rangeSlicesQuery = HFactory
					.createRangeSlicesQuery(keyspaceOperator, stringSerializer,
							stringSerializer, stringSerializer);
			rangeSlicesQuery.setColumnFamily("CF");
			rangeSlicesQuery
					.setColumnNames(new String[] { "col1", "col2" });
			rangeSlicesQuery.setKeys("key", "");

			rangeSlicesQuery.setRowCount(5);
			QueryResult> result = rangeSlicesQuery
					.execute();
			OrderedRows orderedRows = result.get();

			Row lastRow = orderedRows.peekLast();

			System.out.println("Contents of rows: \n");
			for (Row r : orderedRows) {
				System.out.println("   " + r);
			}

		} catch (HectorException he) {
			he.printStackTrace();
		}
		cluster.getConnectionManager().shutdown();
	}
}

0 件のコメント:

コメントを投稿