java Cassandra

public static void test() throws IOException, Exception, TException {
        TTransport tr = new TFramedTransport(new TSocket("localhost", 9160));
        TProtocol proto = new TBinaryProtocol(tr);

        Cassandra.Client client = new Cassandra.Client(proto);
        tr.open();
        String keyspace = "content";
        client.set_keyspace(keyspace);
        // record id
        String key_user_id = "123.com";
        String columnFamily = "Word";
        // insert data
        long timestamp = System.currentTimeMillis();
        Random r = new Random(timestamp);
        Column nameColumn = new Column(ByteBuffer.wrap("word".getBytes()));
        nameColumn.setValue("zhibo".getBytes());
        nameColumn.setTimestamp(timestamp);

        ColumnParent columnParent = new ColumnParent(columnFamily);
        client.insert(ByteBuffer.wrap(key_user_id.getBytes()), columnParent,
                nameColumn, ConsistencyLevel.ALL);

        // Gets column by key
        SlicePredicate predicate = new SlicePredicate();
        predicate.setSlice_range(new SliceRange(ByteBuffer.wrap(new byte[0]),
                ByteBuffer.wrap(new byte[0]), false, 100));
        List<ColumnOrSuperColumn> columnsByKey = client.get_slice(
                ByteBuffer.wrap(key_user_id.getBytes()), columnParent,
                predicate, ConsistencyLevel.ALL);
        System.out.println(columnsByKey);

        // Get all keys
        KeyRange keyRange = new KeyRange(100);
        keyRange.setStart_key(new byte[0]);
        keyRange.setEnd_key(new byte[0]);
        List<KeySlice> keySlices = client.get_range_slices(columnParent,
                predicate, keyRange, ConsistencyLevel.ONE);
        System.out.println(keySlices.size());
        System.out.println(keySlices);
        for (KeySlice ks : keySlices) {
            System.out.println(new String(ks.getKey()));
        }
        tr.close();
    }

posted @ 2011-12-31 14:55  witwave  阅读(319)  评论(0)    收藏  举报