Cassandra – 數據庫啓動和訪問

使用最新的2.0.3版本,解壓後進入文件目錄啓動Cassadra,注意:若是不帶-f參數,在MAC OS X系統中Cassandra會在後臺運行,Ctrl+C也沒法關閉。 java

$ bin/cassandra -f
>> Startup completed! Now serving reads.

Cassandra的文件包中,bin下有自帶的數據庫操做命令行工具cassandra-cli,lib中有可供Java編程訪問的Driver.咱們先介紹命令行工具的基本數據庫操做: 數據庫

$ bin/cassandra-cli
>> Connected to: "Test Cluster" on 127.0.0.1/9160 Welcome to Cassandra CLI version 2.0.3 The CLI is deprecated and will be removed in Cassandra 3.0. Consider migrating to cqlsh. CQL is fully backwards compatible with Thrift data; see http://www.datastax.com/dev/blog/thrift-to-cql3
Type 'help;' or '?' for help. Type 'quit;' or 'exit;' to quit.
>> [default@unknown]

Key space相似於數據庫的概念,首先須要建立一個Key space. apache

$ create keyspace testkeyspace; 
>> cd74ab35-72c3-3c72-a9ef-51a8a17bca18

Cassandra是列數據庫,建立Column family 編程

$ use testkeyspace; 
>> Authenticated to keyspace: testkeyspace
$ create column family testcolumnfamily; 
>> adc59964-8f3a-3a80-bc65-f692405b5278

寫入數據,在此以前先設置Cassandra的字符類型,不然行列名稱會沒法識別: bash

$ assume testcolumnfamily keys as utf8; 
$ assume testcolumnfamily comparator as utf8; 
$ assume testcolumnfamily validator as utf8; 
$ set testcolumnfamily['row']['column1'] = 'avalue'; 
>> Value inserted. Elapsed time: 35 msec(s).

Cassandra有一個頗有趣的功能,自動刪除數據,下面是設置10秒後刪除數據: app

$ set testcolumnfamily['row']['column2'] = 'bvalue' with ttl = 10; 
>> Value inserted. Elapsed time: 35 msec(s).

查看數據 socket

$ list testcolumnfamily 
>> RowKey: row => (name=column1, value=avalue, timestamp=1385639319712) 
$ get testcolumnfamily['row'] 
=> (name=column1, value=avalue, timestamp=1385639319712)

使用Java啓動Cassandra服務時,注意要引用全部cassandra/lib下的文件,不然會連續遇到yaml解析錯誤等問題。
先建立一個Cassandra客戶端: ide

/**
 * User: Justina Chen
 * Date: 11/28/13
 * Time: 5:57 PM
 */ 
import org.apache.cassandra.thrift.Cassandra; 
import org.apache.thrift.protocol.*; 
import org.apache.thrift.transport.*; 

public class FramedConnWrapper {

    private TTransport transport;
    private TProtocol protocol;  
    private TSocket socket;  

    public FramedConnWrapper(String host, int port) { 
        socket = new TSocket(host, port); 
        transport = new TFramedTransport(socket); 
        protocol = new TBinaryProtocol(transport);  
    }
  
    public void open() throws Exception {  
        transport.open();  
    }

    public void close() throws Exception {  
        transport.close();  
        socket.close();  
    }

    public Cassandra.Client getClient() {  
        Cassandra.Client client = new Cassandra.Client(protocol);  
        return client;  
    }
}

在單元測試中啓動Cassandra內置服務,並測試訪問: 工具

/**
 * User: Justina Chen
 * Date: 11/28/13
 * Time: 7:02 PM
 */ 
import junit.framework.Assert; 
import org.apache.thrift.TException; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.Test; 
import org.apache.cassandra.service.*;  

public class UtilTest {  
   
    private static EmbeddedCassandraService cassandraService;  
    private FramedConnWrapper connWrapper;  

    @Before
    public void setUp() throws Exception {  
        cassandraService = new EmbeddedCassandraService();  
        cassandraService.start();  
        connWrapper = new FramedConnWrapper("localhost", 9160);  
        connWrapper.open();  
    }

    @After  
    public void tearDown() throws Exception {
        connWrapper.close();  
    } 

    @Test
    public void testEmbeddedCassandra() throws TException {  
        Assert.assertEquals("Test Cluster", connWrapper.getClient().describe_cluster_name());  
    }
}

數據寫入: 單元測試

/**
 * User: Justina Chen
 * Date: 11/28/13
 * Time: 7:11 PM
 */ 
import java.nio.ByteBuffer; 
import java.util.*; 
import org.apache.cassandra.thrift.*; 

public class GetVMultiGet {  
   
    public static void main (String[] args) throws Exception {  
        FramedConnWrapper fcw = new FramedConnWrapper("localhost", 9160);  
        fcw.open();  

        ColumnParent parent = new ColumnParent();  
        parent.setColumn_family("testcolumnfamily");  
        ColumnPath path = new ColumnPath();  
        path.setColumn_family("testcolumnfamily"); 
        path.setColumn("column1".getBytes("UTF-8"));  
        Column c = new Column();  
        fcw.getClient().set_keyspace("testkeyspace"); 
        c.setName("column1".getBytes());  
        c.setTimestamp(System.currentTimeMillis());  

        for (int j = 0; j < inserts; j++) {  
            byte[] key = (j+"").getBytes(); 
            ByteBuffer keyBuf = ByteBuffer.wrap(key);  
            c.setValue(key);  
            fcw.getClient().insert(keyBuf, parent, c, ConsistencyLevel.ALL); 
            fcw.getClient().get(keyBuf, path, ConsistencyLevel.ALL);  
        }

        long getNanos = System.nanoTime();  
        for (int j = 0; j < inserts; j++) {  
            byte[] key = (j+"").getBytes();  
            c.setValue(key);  
            fcw.getClient().get(ByteBuffer.wrap(key), path, ConsistencyLevel.ONE);  
        }  

        long endGetNanos = System.nanoTime() - getNanos;   
        System.out.println("get time " + endGetNanos); 
        fcw.close();  
    } 
}

對Cassandra初次印象是,操做和訪問都比較複雜,出錯時沒有一個清楚的提示,加上文檔不多,和其它NoSQL數據庫尤爲是MongoDB比起來,可用性還比較低。

原文連接:Cassandra – 數據庫啓動和訪問

相關文章
相關標籤/搜索