本文介绍通过Cassandra CQL Java Driver连接并使用Lindorm。

前提条件

创建连接

 String[] contactPoints = new String[]{
      "ip"//从控制台获取的连接地址,只用写ip,不要写端口!
 };
  
 Cluster cluster = Cluster.builder()
      .addContactPoints(contactPoints)      // 填写账户名密码(控制台获取)
      .withAuthProvider(new PlainTextAuthProvider(username, password))
      .build();
 cluster.init();//初始化集群连接,会建立控制
 Session session = cluster.connect();//初始化连接session,不能每个请求创建一个Session。合理的应该是每个进程预先创建若干个。

适用Driver执行操作

DDL操作

 // 创建keyspace,指定对应strategy, replication factor。
    session.execute(
                "CREATE KEYSPACE IF NOT EXISTS testKeyspace WITH replication "
                        + "= {'class':'SimpleStrategy', 'replication_factor':1};");

 // 创建table,给table指定对应的primary key 以及cluster key 和regular key
    session.execute(
                "CREATE TABLE IF NOT EXISTS testKeyspace.testTable ("
                        + "id int PRIMARY KEY,"
                        + "name text,"
                        + "age int,"
                        + "address text"
                        + ");");    

 //清空表
    session.execute("TRUNCATE TABLE testKeyspace.testTable;");
 //删除表
    session.execute("DROP TABLE testKeyspace.testTable ");

DML操作

    // 执行insert 操作
    session.execute(
                "INSERT INTO testKeyspace.testTable (id, name, age, address) "
                        + "VALUES ("
                        + "1,"
                        + "'testname',"
                        + "11,"
                        + "'hangzhou');");
    // 执行select 操作,这里select * 表示获取所有列,也可以指定需要select 的列名获取对应列数据
    ResultSet res = session.execute(
                "SELECT * FROM testKeyspace.testTable ;");

    // 如果想要获取每一列对应的数据,可以如下操作
    for (Row row : results)
    {
        int id = row.getInt("id");
        String name = row.getString("name");
        int age = row.getInt("age");
        String address = row.getString("address");
    }

    // 关闭Session
    session.close();
    // 关闭Cluster
    cluster.close();