如何使用Java类连接Cassandra [英] How to connect Cassandra using Java class

查看:585
本文介绍了如何使用Java类连接Cassandra的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样做连接cassandra.But我的代码返回一个错误..这是我的代码

  CassandraConnection {

public static void main(String [] args){
String serverIp =166.78.10.41;
String keyspace =gamma;
CassandraConnection连接;

集群集群= Cluster.builder()
.addContactPoints(serverIp)
.build();

会话session = cluster.connect(keyspace);


String cqlStatement =SELECT * FROM TestCF;
for(Row row:session.execute(cqlStatement)){
System.out.println(row.toString());
}

}
}

错误日志..

 无法在项目上执行目标CassandraConnection:无法解决项目com.mycompany的依赖项:CassandraConnection:jar :1.0-SNAPSHOT:无法解析以下工件:org.specs2:scalaz-effect_2.11.0-SNAPSHOT:jar:7.0.1-SNAPSHOT,org.scalaz:scalaz-effect_2.9.3:jar:7.1.0-SNAPSHOT :找不到工件org.specs2:scalaz-effect_2.11.0-SNAPSHOT:jar:7.0.1-SNAPSHOT  - > [帮助1] 

要查看错误的完整堆栈跟踪, e开关。
使用-X开关重新运行Maven以启用完整的调试日志记录。



有关错误和可能的解决方案的更多信息,请阅读以下文章:
[帮助1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

解决方案

您有关于此事的任何研究吗?



< h2>选择驱动程序

您需要一种与cassandra通信的方法,最好的选择是使用高级API。你在这里有很多选择,但是当我们从高水平的角度来看时,实际上有两种选择。


  1. 基于CQL的驱动程序 - 更高级别的抽象代码。

  2. 基于Thrift的驱动器 - 可以访问低级存储,因此更容易出错。

我会使用 datastax的CQL驱动程序



从datastax的github repo OR 下载并构建驱动程序,以下依赖关系:

 < dependency> 
< groupId> com.datastax.cassandra< / groupId>
< artifactId> cassandra-driver-core< / artifactId>
< version> 2.1.3< / version>
< / dependency>

< dependency>
< groupId> com.datastax.cassandra< / groupId>
< artifactId> cassandra-driver-mapping< / artifactId>
< version> 2.1.2< / version>
< / dependency>

选择maven是一个好主意,因为它会管理你的所有依赖项,


h2>代码

驱动程序的文档来得很好。



我将在整个示例中使用以下两个变量。

  String serverIP =127.0.0.1; 
String keyspace =system;

集群集群= Cluster.builder()
.addContactPoints(serverIP)
.build();

会话session = cluster.connect(keyspace);

//你现在连接到集群,congrats!

阅读

  String cqlStatement =SELECT * FROM local; 
for(row row:session.execute(cqlStatement)){
System.out.println(row.toString());
}

创建/更新/删除

  //对于所有三个它的工作方式相同(注意系统键空间不能
//由用户修改所以下面的im使用一个键空间名称'exampkeyspace'和
//一个表(或列家庭)调用users

String cqlStatementC =INSERT INTO exampkeyspace.users(username,password)+
VALUES('Serenity','fa3dfQefx');

String cqlStatementU =UPDATE exampkeyspace.users+
SET password ='zzaEcvAf32hla',+
WHERE username ='Serenity';;

String cqlStatementD =DELETE FROM exampkeyspace.users+
WHERE username ='Serenity';;

session.execute(cqlStatementC); //可互换,放任何语句u wish。




其他有用的代码



创建键空间 p>

  String cqlStatement =CREATE KEYSPACE myfirstcassandradb WITH+ 
replication = {'class':'SimpleStrategy','replication_factor ':1};

session.execute(cqlStatement);

创建ColumnFamily(aka表)

  //基于上述键空间,我们将更改集群和会话如下:
集群集群= Cluster.builder()
.addContactPoints(serverIP)
.build();
会话session = cluster.connect(myfirstcassandradb);

String cqlStatement =CREATE TABLE users(+
user_name varchar PRIMARY KEY,+
password varchar+
);;

session.execute(cqlStatement);


I am doing this to connect cassandra.But my code is returning an error.. Here is my code

public class CassandraConnection {

public static void main(String[] args) {
    String serverIp = "166.78.10.41";
    String keyspace = "gamma";
    CassandraConnection connection;

    Cluster cluster = Cluster.builder()
            .addContactPoints(serverIp)
            .build();

    Session session = cluster.connect(keyspace);


    String cqlStatement = "SELECT * FROM TestCF";
    for (Row row : session.execute(cqlStatement)) {
        System.out.println(row.toString());
    }

}
}

this is the error log ..

 Failed to execute goal on project CassandraConnection: Could not resolve dependencies      for project com.mycompany:CassandraConnection:jar:1.0-SNAPSHOT: The following artifacts could not be resolved: org.specs2:scalaz-effect_2.11.0-SNAPSHOT:jar:7.0.1-SNAPSHOT, org.scalaz:scalaz-effect_2.9.3:jar:7.1.0-SNAPSHOT: Could not find artifact org.specs2:scalaz-effect_2.11.0-SNAPSHOT:jar:7.0.1-SNAPSHOT -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch. Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles: [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

解决方案

Did you do any research on the matter?

Picking a driver

You need a way to communicate with cassandra, best option is to use a high level API. You have a wide range of choices here but when we look at it from a high level prespective there are really two choices.

  1. CQL based drivers - Higher level abstraction of what thrift does. Also the newer tool, companies providing support / documentation for cassandra recommend that new cassandra applications are CQL based.
  2. Thrift based drives - Have access to low level storage, so its easier to get things wrong.

I'll use datastax's CQL driver.

Download and build the driver from datastax's github repo OR use maven and add the following dependencies:

<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-core</artifactId>
  <version>2.1.3</version>
</dependency>

<dependency>
  <groupId>com.datastax.cassandra</groupId>
  <artifactId>cassandra-driver-mapping</artifactId>
  <version>2.1.2</version>
</dependency>

Picking maven is a good idea, as it will manage all your dependencies for you, but if you dont use maven, at least you will learn about managing jars and reading through stack-traces.


Code

The driver's documentation is coming along nicely. If you get stuck read through it, the documentation contains lots of examples.

I'll use the following two variables throughout the examples.

String serverIP = "127.0.0.1";
String keyspace = "system";

Cluster cluster = Cluster.builder()
  .addContactPoints(serverIP)
  .build();

Session session = cluster.connect(keyspace);

// you are now connected to the cluster, congrats!

Read

String cqlStatement = "SELECT * FROM local";
for (Row row : session.execute(cqlStatement)) {
  System.out.println(row.toString());
}

Create/Update/Delete

// for all three it works the same way (as a note the 'system' keyspace cant 
// be modified by users so below im using a keyspace name 'exampkeyspace' and
// a table (or columnfamily) called users

String cqlStatementC = "INSERT INTO exampkeyspace.users (username, password) " + 
                      "VALUES ('Serenity', 'fa3dfQefx')";

String cqlStatementU = "UPDATE exampkeyspace.users" +
                      "SET password = 'zzaEcvAf32hla'," +
                      "WHERE username = 'Serenity';";

String cqlStatementD = "DELETE FROM exampkeyspace.users " + 
                      "WHERE username = 'Serenity';";

session.execute(cqlStatementC); // interchangeable, put any of the statements u wish.


Other useful code

Creating a Keyspace

String cqlStatement = "CREATE KEYSPACE myfirstcassandradb WITH " + 
  "replication = {'class':'SimpleStrategy','replication_factor':1}";

session.execute(cqlStatement);

Creating a ColumnFamily (aka table)

// based on the above keyspace, we would change the cluster and session as follows:
Cluster cluster = Cluster.builder()
  .addContactPoints(serverIP)
  .build();
Session session = cluster.connect("myfirstcassandradb");

String cqlStatement = "CREATE TABLE users (" + 
                      " user_name varchar PRIMARY KEY," + 
                      " password varchar " + 
                      ");";

session.execute(cqlStatement);

这篇关于如何使用Java类连接Cassandra的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆