2011年9月30日金曜日

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

CassandraへHectorを使用してアクセスを行う。
今回は、CQLを使ったアクセスを試みます。

package com.zomu.t;

import java.nio.charset.CharacterCodingException;

import me.prettyprint.cassandra.model.CqlQuery;
import me.prettyprint.cassandra.model.CqlRows;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.beans.HColumn;
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.query.QueryResult;

/**
 * CQLアクセステスト
 * @author nozomu
 */
public class AccessTestCql {

	/** 文字列シリアライザ */
	private static StringSerializer stringSerializer = StringSerializer.get();

	/**
	 *
	 * @param args
	 * @throws CharacterCodingException
	 */
	public static void main(String[] args) throws CharacterCodingException {

		// クラスタ
		Cluster cluster = HFactory.getOrCreateCluster("TestCluster",
				"localhost:9160");
		// 使用するKeySpace
		Keyspace keyspaceOperator = HFactory.createKeyspace("Giraffe", cluster);

		try {

			// CQLクエリを発行するクラス
			CqlQuery<String, String, String> cqlQuery = new CqlQuery<String, String, String>(
					keyspaceOperator, stringSerializer, stringSerializer,
					stringSerializer);
			// CQLを設定
			cqlQuery.setQuery("select * from CF where key = 'key'");

			// 取得する
			QueryResult> result = cqlQuery
					.execute();

			if (result != null) {
				CqlRows rows = result.get();

				if (rows != null) {
					for (Row row : rows.getList()) {
						for (HColumn col : row.getColumnSlice()
								.getColumns()) {
							System.out.println(col.getName() + " : "
									+ col.getValue());
						}
					}
				}
			}
		} catch (HectorException he) {
			he.printStackTrace();
		}
		cluster.getConnectionManager().shutdown();
	}
}


CQLはこれからCassandraを使用する場合には必須となりそうな予感がする。
ObjectMapper等もHectorには用意してあるみたいなので、併せてこちらも試す事にしようと思う。
それはまた次回にでも。

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();
	}
}

Mac OSX のデフォルトのJava

Macを買ってJavaがらみのなにかをなにもしていなければ、
デフォルト状態のJavaの設定になっているはず。

ターミナルを起動し、以下で確認が可能。
>which java
/usr/bin/java
>
>java -version
java version "1.6.0_22"
Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)

CassandraでCQLを使う

少し前からCassandraに興味を持って、使い始めてます。
最初にインストールしてから0.6→0.7→0.8とめまぐるしくリリースされて困りますね。
特に0.8でCQLの登場にはちょっと愕然としました。
なんだよー。そーゆーことやるんなら最初から出せよー。ってな具合で。。。

もう古いバージョンのメモを残してもしゃーないので、CQLを使ったアクセスからメモをしていこうと思っとる次第です。

package com.zomu.t.cql;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.Compression;
import org.apache.cassandra.thrift.CqlResult;
import org.apache.cassandra.thrift.CqlResultType;
import org.apache.cassandra.thrift.CqlRow;
import org.apache.cassandra.utils.ByteBufferUtil;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;

public class CassandraAccessSample {

 public static void main(String[] args) {
  try {
   TSocket transport = new TSocket("localhost", 9160);
   TFramedTransport framedTransport = new TFramedTransport(transport);
   TProtocol protocol = new TBinaryProtocol(framedTransport);
   Cassandra.Client client = new Cassandra.Client(protocol);
   transport.open();

   client.set_keyspace("TestKeySpace");
   CqlResult result = client
     .execute_cql_query(
       ByteBufferUtil
         .bytes("select * from CF where key = key_1;"),
       Compression.NONE);
   if (CqlResultType.ROWS.equals(result.getType())) {
    System.out.println("HIT->"+result.rows.size()+"\n");
    for (CqlRow row : result.rows) {
     for (Column col : row.columns) {
      System.out.println(ByteBufferUtil.string(col.name) + "="
        + new String(col.getValue()));
     }
     System.out.println("-----------------");
    }
   }
   transport.close();
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
 

今回はCassandraのサンプルで一般的にあるThriftを利用したクライアントで接続する方法です。
Webアプリケーション等でCassandraを使用する場合にはこのような接続方法は推奨されません。
僕はしてて、かなりひどい状態になりました。。。。

CassandraのWikiを見ると、高度なクライアントなんて感じで紹介されているので使っていこうかと思います。
予定ではHector

2011年9月29日木曜日

メモをコードも一緒に残したい

大変恐縮ながら、僕もWEB上にメモをしようかと。
なので、コードも載せれるように準備しました。

// ほげ
String hoge = new String();


こんな感じで書く訳ですね。

2011年9月15日木曜日

Castor

Castorを使用した、Javaオブジェクト→XMLをやってみた。
とても簡単にできるのでとてもおすすめ。

今回は、XSLTによる変換を行いたいため使用した。
つか、このブログってソース載せることできるかな。。。
なんだっけ。Wikiとかでもソース載せるのに便利な…あれ。忘れちゃった。。。