Step by Step C# operate NOSQL base on Cassandra
2010年NOSQL技术似乎是发展最快的几个概念之一,相信好多朋友也都和我一样,愿意尝试新东西,网络上面关于NOSQL的东西还不是很多,你也可以说很多,但是大部分是复制粘贴的,不成什么体系,也可能是本人眼界有限,如果有的话望高人指点。另一方面,NOSQL这个东西发展很快,好多CODE在有些版本上面可以RUN,但是版本更新了就不行了。其实我的目的很简单,用C#写一个Demo, 向Cassandra里面写条数据,然后再读出来,下面,Let’s go!
1.首先配置Cassandra,去http://cassandra.apache.org/上面下一个最新的就ok了
我用的是这个:apache-cassandra-0.7.3-bin.tar.gz
2.解压缩上面的包,并安装Java 虚拟机并配置环境变量JAVA_HOME, CASSANDRA_HOME, 分别设置为Java路径和解压缩后的Cassandra路径。
3. 用cassandra.bat 启动Cassandra, 可以用cassandra-cli.bat 测试一下你的Cassandra数据库。
4. 去http://thrift.apache.org/下载一个最新版本的Thrift,解压缩并取出
thrift-0.6.0\thrift\lib\csharp\src Thrift.sln,build it 得到一个Thrift.dll。
5. 去http://thrift.apache.org/ 下载一个最新版本的Thrift.exe
切换到cassandra的interface目录, run thrift -gen csharp cassandra.thrift 命令, 生成: gen-csharp folder
6. 建一个C#工程, 把gen-csharp folder下面的code加进去,并且添加引用Thrift.dll。
7.写CODE, 下面是我参照网上的资料写的一个简单Demo:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Thrift.Transport;
using Thrift.Protocol;
using Apache.Cassandra;
//If the keyspace or column family not exist we need add them using the following cmd
/* Create a new keyspace */
//create keyspace Keyspace1;
/* Switch to the new keyspace */
//use Keyspace1;
/* Create new column families */
//create column family Standard1 with column_type = 'Standard' and comparator = 'BytesType';
namespace ConsoleCassandraDemo
{
class Program
{
static void Main(string[] args)
{
//Data define
System.Text.Encoding utf8Encoding = System.Text.Encoding.UTF8;
long timeStamp = DateTime.Now.Millisecond;
//Server Location
TTransport FTransport = new TFramedTransport(new TSocket("localhost", 9160));
TProtocol FProtocol = new TBinaryProtocol(FTransport);
Cassandra.Client client = new Cassandra.Client(FProtocol, FProtocol);
FTransport.Open();
Console.WriteLine("Connection...");
client.set_keyspace("Keyspace1");
Console.WriteLine("Set keyspace...");
ColumnPath nameColumnPath = new ColumnPath()
{
Column_family = "Standard1",
Column = utf8Encoding.GetBytes("name")
};
ColumnParent nameColumnParent = new ColumnParent()
{
Column_family = "Standard1"
};
Column nameColume = new Column()
{
Name = utf8Encoding.GetBytes("name"),
Value = utf8Encoding.GetBytes("Drift UFO2"),
Timestamp = timeStamp
};
Console.WriteLine("Inserting name columns");
//Insert column names
client.insert(utf8Encoding.GetBytes("KKP"),
nameColumnParent,
nameColume,
ConsistencyLevel.ONE);
//Get the value using key
ColumnOrSuperColumn returnedColumn = client.get(utf8Encoding.GetBytes("KKP"), nameColumnPath, ConsistencyLevel.ONE);
Console.WriteLine(
"Column Data in Keyspace1/Standard1: name: {0}, value: {1}",
utf8Encoding.GetString(returnedColumn.Column.Name),
utf8Encoding.GetString(returnedColumn.Column.Value));
Console.WriteLine("Connection closing");
FTransport.Close();
Console.ReadLine();
}
}
}
8.Please run this code after start the Cassandra, Enjoy…