波斯马BOSSMA Information Technology

在.NET平台下使用C#通过Thrift访问Cassandra

发布时间:2011年11月17日 / 分类:DataBase, NoSQL / 19,718 次浏览 / 评论

前一篇文章介绍了在Windows下安装Cassandra的步骤,这一篇文章将介绍在.NET平台下使用C#通过Thrift访问Cassandra。Thrift是Facebook使用的一个跨语言通信工具,提供了很多语言版本的支持。

1、下载Thrift

两个文件:

thrift-0.7.0.tar.gz

Thrift compiler for Windows

2、获取Thrift.dll

解压后,找到源代码:

thrift-0.7.0\lib\csharp\src,在Visual Studio中打开Thrift.csproj,重新编译生成dll。

3、生成C#代码

将thrift-0.7.0.exe复制到Cassandra安装目录的interface目录中。

在命令提示符工具中进入interface目录,执行以下命令:

thrift-0.7.0.exe --gen csharp cassandra.thrift

完毕后会在这个目录中生成一个文件夹:gen-csharp。

4、获取Apache.Cassandra.dll

新建一个类库项目,把这些文件加到这个项目中,编译生成一个dll文件。

别忘了添加引用上边生成的Thrift.dll文件。

5、编写测试程序

在Visual Studio中创建一个项目,这里以用户令牌为例,给出两个方法:

(1)、插入数据

public string SetUserToken()
        {
            string keySpaceName = "UserTokenSpace";
            string columnFamilyName = "UserToken";
            string columnName = "Token";
            string key = "1001";
            string token = "we9g872m9f5l";
            Encoding utf8Encoding = Encoding.UTF8;
            long timeStamp = DateTime.Now.Ticks;

            TTransport frameTransport = null;
            try
            {
                // 通过Thrift建立到Cassandra的连接
                frameTransport = new TFramedTransport(new TSocket("localhost", 9160));
                TProtocol protocol = new TBinaryProtocol(frameTransport);
                TProtocol frameProtocol = new TBinaryProtocol(frameTransport);
                Cassandra.Client client = new Cassandra.Client(protocol, frameProtocol);
                frameTransport.Open();

                // 先删除已经创建的KeySpace,以便于测试
                try
                {
                    client.system_drop_keyspace(keySpaceName);
                }
                catch
                {
                }

                // KeySpace 定义
                KsDef ks = new KsDef()
                {
                    Name = keySpaceName,
                    Replication_factor = 1,
                    Strategy_class = "org.apache.cassandra.locator.SimpleStrategy",

                    // Column Family 定义
                    Cf_defs = new List<CfDef>() {
                        new CfDef(){
                                        Name = columnFamilyName,
                                        Keyspace = keySpaceName,
                                        Comparator_type = "BytesType",

                                        // Column 定义
                                        Column_metadata = new List<ColumnDef>(){
                                            new ColumnDef(){
                                                Index_name = columnName,
                                                Index_type = IndexType.KEYS,
                                                Name = utf8Encoding.GetBytes("Token"),
                                                Validation_class = "BytesType"
                                            }
                                        }
                                    }
                    }
                };

                // 添加KeySpace
                client.system_add_keyspace(ks);

                //设置当前KeySpace
                client.set_keyspace(keySpaceName);

                // 要插入数据的路径
                ColumnParent tokenColumnParent = new ColumnParent()
                {
                    Column_family = columnFamilyName
                };

                // 要插入数据的Column
                Column tokenColume = new Column()
                {
                    Name = utf8Encoding.GetBytes(columnName),
                    Value = utf8Encoding.GetBytes(token),
                    Timestamp = timeStamp
                };

                //插入数据
                client.insert(utf8Encoding.GetBytes(key), tokenColumnParent, tokenColume, ConsistencyLevel.ONE);
            }
            finally
            {
                if (frameTransport != null)
                {
                    frameTransport.Close();
                }
            }

            return token;
        }

(2)、获取数据

public static string GetUserToken(string userId)
        {
            string keySpaceName = "UserTokenSpace";
            string columnFamilyName = "UserToken";
            string columnName = "Token";
            System.Text.Encoding utf8Encoding = System.Text.Encoding.UTF8;
            long timeStamp = DateTime.Now.Millisecond;

            TTransport frameTransport = null;
            try
            {
                // 通过Thrift建立到Cassandra的连接
                frameTransport = new TFramedTransport(new TSocket("localhost", 9160));
                TProtocol protocol = new TBinaryProtocol(frameTransport);
                TProtocol frameProtocol = new TBinaryProtocol(frameTransport);
                Cassandra.Client client = new Cassandra.Client(protocol, frameProtocol);
                frameTransport.Open();

                // 设置当前KeySpace
                client.set_keyspace(keySpaceName);

                // 查找路径
                ColumnPath nameColumnPath = new ColumnPath()
                {
                    Column_family = columnFamilyName,
                    Column = utf8Encoding.GetBytes(columnName)
                };

                // 获取Column
                ColumnOrSuperColumn returnedColumn = client.get(utf8Encoding.GetBytes(userId), nameColumnPath, ConsistencyLevel.ONE);
                return utf8Encoding.GetString(returnedColumn.Column.Value);
            }
            catch
            {
            }
            finally
            {
                // 别忘了关闭连接
                if (frameTransport != null)
                {
                    frameTransport.Close();
                }
            }

            return string.Empty;
        }

 

使用ThriftAPI进行数据操作还是很繁琐的,nosql的操作规范没有sql那么好啊,不过效率肯定有保证。接下来的文章会介绍一些高级API的使用。

本博客所有文章如无特别注明均为原创。
复制或转载请以超链接形式注明转自波斯马,原文地址《在.NET平台下使用C#通过Thrift访问Cassandra

关键字:

建议订阅本站,及时阅读最新文章!
【上一篇】 【下一篇】

目前有2 条评论

  1. bossma 0楼:

    @八龙
    因为一般只通过key来进行查询,所以这个key应该是个有意义的值。当然还可以通过建立索引来查询某个column。

  2. 八龙 0楼:

    我也用这个呢,你们那里key的值怎么存呀?存的就是ID吗?还是些有意义的值?

发表评论