카 산 드 라 가 데 이 터 를 추가, 업데이트, 삭제 합 니 다.

27188 단어 자바cassandra
package client;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.util.List;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.SlicePredicate;
import org.apache.cassandra.thrift.SliceRange;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class CClient
{
    public static void main(String[] args)
    throws TException, InvalidRequestException, UnavailableException, UnsupportedEncodingException, NotFoundException, TimedOutException
    {
        //    
        TTransport tr = new TFramedTransport(new TSocket("127.0.0.1", 9160));
        TProtocol proto = new TBinaryProtocol(tr);
        Cassandra.Client client = new Cassandra.Client(proto);
        tr.open();

        String key_user_id = "1";

        // insert data
        long timestamp = System.currentTimeMillis();
        //   DB NAME
        client.set_keyspace("DEMO");      
        //   DB Table
        ColumnParent parent = new ColumnParent("Users");
        //   
        Column nameColumn = new Column(toByteBuffer("name"));
        //   
        nameColumn.setValue(toByteBuffer("scott"));
        //    
        nameColumn.setTimestamp(timestamp);
        //      cassandra
        client.insert(toByteBuffer(key_user_id), parent, nameColumn, ConsistencyLevel.ONE);
        //   
        Column ageColumn = new Column(toByteBuffer("password"));
        //   
        ageColumn.setValue(toByteBuffer("tiger"));
        //    
        ageColumn.setTimestamp(timestamp);
        //      cassandra
        client.insert(toByteBuffer(key_user_id), parent, ageColumn, ConsistencyLevel.ONE);
        //     DB Table
        ColumnPath path = new ColumnPath("Users");

        // read single column
        path.setColumn(toByteBuffer("name"));
        System.out.println(client.get(toByteBuffer(key_user_id), path, ConsistencyLevel.ONE));

        // read entire row
        SlicePredicate predicate = new SlicePredicate();
        SliceRange sliceRange = new SliceRange(toByteBuffer(""), toByteBuffer(""), false, 10);
        predicate.setSlice_range(sliceRange);
        
        List results = client.get_slice(toByteBuffer(key_user_id), parent, predicate, ConsistencyLevel.ONE);
        for (ColumnOrSuperColumn result : results)
        {
            Column column = result.column;
            System.out.println(toString(column.name) + " -> " + toString(column.value));
        }

        tr.close();
    }
    
    public static ByteBuffer toByteBuffer(String value) 
    throws UnsupportedEncodingException
    {
        return ByteBuffer.wrap(value.getBytes("UTF-8"));
    }
        
    public static String toString(ByteBuffer buffer) 
    throws UnsupportedEncodingException
    {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        return new String(bytes, "UTF-8");
    }
}

 
package result;
import java.nio.ByteBuffer;

import org.apache.cassandra.thrift.Cassandra;
import org.apache.cassandra.thrift.Column;
import org.apache.cassandra.thrift.ColumnOrSuperColumn;
import org.apache.cassandra.thrift.ColumnParent;
import org.apache.cassandra.thrift.ColumnPath;
import org.apache.cassandra.thrift.ConsistencyLevel;
import org.apache.cassandra.thrift.InvalidRequestException;
import org.apache.cassandra.thrift.NotFoundException;
import org.apache.cassandra.thrift.TimedOutException;
import org.apache.cassandra.thrift.UnavailableException;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

public class CassandraTest {
    static Cassandra.Client cassandraClient;
    static TTransport socket;

    private static void init(String keySpace) throws InvalidRequestException, TException {
        String server = "127.0.0.1";
        int port = 9160;
        /*         */
        socket = new TSocket(server, port);
        System.out.println(" connected to " + server + ":" + port + ".");
        TFramedTransport transport = new TFramedTransport(socket);
        /*               */
        TBinaryProtocol binaryProtocol = new TBinaryProtocol(transport);
        cassandraClient = new Cassandra.Client(binaryProtocol);
        /*        */
        socket.open();
        cassandraClient.set_keyspace(keySpace);
    }

    public static void main(String[] args) throws TException, TimedOutException,
            InvalidRequestException, UnavailableException, NotFoundException {
        /*        ,         */
        String keyspace = "DEMO";

        /*       */
        init(keyspace);

        /*       */
        String columnFamily = "Users";
        //KEY   
        String tablename = "myinfo";

        /*        */
        insertOrUpdate(columnFamily, tablename, "fengye", "  ", System.currentTimeMillis());
        /*        */
        //delete(columnFamily,tablename,"fengye",System.currentTimeMillis());
        /*        (             ,         !     ! */
        Column column = getByColumn(columnFamily, tablename, "fengye", System.currentTimeMillis());

        System.out.println("read Table " + columnFamily);
        System.out.println("read column name " + ":" + toString(column.name));
        System.out.println("read column value" + ":" + toString(column.value));
        System.out.println("read column timestamp" + ":" + (column.timestamp));
        close();
    }

    /**
     *     
     */
    public static void insertOrUpdate(    String columnFamily,
                                        String tableName,
                                        String ColumnName,
                                        String ColumnValue,
                                        long timeStamp) throws TException, TimedOutException,
            InvalidRequestException, UnavailableException, NotFoundException {
        /*     column path */
        ColumnParent parent = new ColumnParent(columnFamily);
        Column col = new Column(CassandraTest.toByteBuffer(ColumnName));
        col.setValue(CassandraTest.toByteBuffer(ColumnValue));
        col.setTimestamp(System.currentTimeMillis());
        try{
            /*
             *       ,  keysapce, row, col,      ,          timestamp,
             *      consistency_level timestamp            ,
             *  consistency_level            ,        bigtable,         dynamo
             */
            cassandraClient.insert(    CassandraTest.toByteBuffer(tableName),
                                    parent,
                                    col,
                                    ConsistencyLevel.ONE);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     *     
     */
    public static void delete(    String columnFamily,
                                String tablename,
                                String ColumnName,
                                long timeStamp) throws TException, TimedOutException,
            InvalidRequestException, UnavailableException, NotFoundException {
        /*        Keyspaces,              */
        /*         */
        /*     column path */
        ColumnPath col = new ColumnPath(columnFamily);
        col.setColumn(CassandraTest.toByteBuffer(ColumnName));
        try{
            /*
             *       ,  keysapce, row, col,          timestamp,
             *      consistency_level timestamp            ,
             *  consistency_level            ,        bigtable,         dynamo
             */
            cassandraClient.remove(    CassandraTest.toByteBuffer(tablename),
                                    col,
                                    System.currentTimeMillis(),
                                    ConsistencyLevel.ONE);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    /**
     *     
     */
    public static Column getByColumn(    String columnFamily,
                                        String tablename,
                                        String ColumnName,
                                        long timeStamp) throws TException, TimedOutException,
            InvalidRequestException, UnavailableException, NotFoundException {
        try{
            /*
             *       ,  keysapce, row, col, timestamp timestamp            ,
             *  consistency_level            ,        bigtable,         dynamo
             */
            /*     columnFamily */
            ColumnPath col = new ColumnPath(columnFamily);
            col.setColumn(CassandraTest.toByteBuffer(ColumnName));
            System.out.println(tablename);
            System.out.println(ColumnName);
            System.out.println(cassandraClient.get(toByteBuffer(tablename), col, ConsistencyLevel.ONE));
            ColumnOrSuperColumn superColumn = cassandraClient.get(    CassandraTest.toByteBuffer(tablename),
                                                                    col,
                                                                    ConsistencyLevel.ONE);
            System.out.println(">>>>>>>>>>>>>>>>" + superColumn);
    
            Column column = cassandraClient.get(CassandraTest.toByteBuffer(tablename),
                                                col,
                                                ConsistencyLevel.ONE).column;
            return column;
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }

    /**
     *            
     */
    public static void close() {
        socket.close();
    }
    
    //  Byte
    public static ByteBuffer toByteBuffer(String value)
    {
        try{
            return ByteBuffer.wrap(value.getBytes("UTF-8"));
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
    //     
    public static String toString(ByteBuffer buffer)
    {
        try{
            byte[] bytes = new byte[buffer.remaining()];
            buffer.get(bytes);
            return new String(bytes, "UTF-8");
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

 
/**
 * 
 */
package result;

import java.util.HashMap;
import java.util.Map;

import me.prettyprint.cassandra.model.AllOneConsistencyLevelPolicy;
import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.FailoverPolicy;
import me.prettyprint.cassandra.service.template.ColumnFamilyResult;
import me.prettyprint.cassandra.service.template.ColumnFamilyTemplate;
import me.prettyprint.cassandra.service.template.ColumnFamilyUpdater;
import me.prettyprint.cassandra.service.template.ThriftColumnFamilyTemplate;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.exceptions.HectorException;
import me.prettyprint.hector.api.factory.HFactory;

public class GetResult {

    /**
     * @param args
     */
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
        String keySpace = "DEMO";//   DB NAME
        String columnFamily = "Users";//   DB Table
        Cluster cluster = HFactory.getOrCreateCluster("Test Cluster",
                "127.0.0.1:9160");
        Map accessMap = new HashMap();
        accessMap.put("username", "wyq");
        accessMap.put("password", "123456");
        Keyspace ksp = HFactory.createKeyspace(keySpace, cluster,
                new AllOneConsistencyLevelPolicy(),
                FailoverPolicy.ON_FAIL_TRY_ALL_AVAILABLE, accessMap);
        ColumnFamilyTemplate template = new ThriftColumnFamilyTemplate(
                ksp, columnFamily, StringSerializer.get(), StringSerializer
                        .get());


        ColumnFamilyUpdater updater = template.createUpdater("u_1");
        //   name,email,time     
        updater.setString("name", "wyqa");
        //updater.setString("email", "[email protected]");
        updater.setString("password", "123456");
        //updater.setLong("time", System.currentTimeMillis());
        
        try {
            template.update(updater);
            System.out.println("update ok.");
        } catch (HectorException e) {
            e.printStackTrace();
        }


        try {
            ColumnFamilyResult res = template
                    .queryColumns("u_1");
            ColumnFamilyResult rest = template
            .queryColumns("1");
            String name = res.getString("name");
            String email = res.getString("email");
            //long time = res.getLong("time");
            System.out.println("read u_1 name:" + name);
            System.out.println("read u_1 email:" + email);
            //System.out.println("read u_1 time:" + time);
            
            System.out.println("age:" + rest.getString("age"));
            System.out.println("name:" + rest.getString("name"));
        } catch (HectorException e) {
            e.printStackTrace();
        }

    }


}

좋은 웹페이지 즐겨찾기