栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何使用Java类连接Cassandra

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何使用Java类连接Cassandra

您对此事有研究吗?

选司机

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

  1. 基于CQL的驱动程序 -节俭功能的高级抽象。同样,较新的工具(为cassandra提供支持/文档​​的公司)建议新的cassandra应用程序基于CQL。
  2. 基于节俭的驱动器 -可以访问低级存储,因此更容易出错。

我将使用datastax的CQL驱动程序。

从datastax的github repo下载并构建驱动程序, 或者 使用maven并添加以下依赖项:

<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是一个好主意,因为它将为您管理所有依赖关系,但是,如果您不使用maven,至少您将了解有关管理jar和读取堆栈跟踪的知识。

该驱动程序的文档很好。如果您不懂它,文档中将包含许多示例。

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

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!

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

创建/更新/删除

// 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 usersString 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.

其他有用的代码

创建一个键空间

String cqlStatement = "CREATE KEYSPACE exampkeyspace WITH " +   "replication = {'class':'SimpleStrategy','replication_factor':1}";session.execute(cqlStatement);

创建一个ColumnFamily(又名表)

// 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("exampkeyspace");String cqlStatement = "CREATE TABLE users (" + " username varchar PRIMARY KEY," + " password varchar " + ");";session.execute(cqlStatement);


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430861.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号