Docker 快速构建 Cassandra 和 Java 操作

Docker 快速构建 Cassandra 和 Java 操作

搭建Cassandra

使用docker创建Cassandra,方便快捷

docker pull cassandra:latest
docker run -d --name cassandra -p 9042:9042 cassandra
docker exec -it cassandra bash

创建keyspace、table

#cqlsh>
#create keyspace
CREATE KEYSPACE contacts WITH REPLICATION = {
	'class' : 'SimpleStrategy',
	'replication_factor' : 1 
};
#use
USE contacts;
#create table
CREATE TABLE contact ( 
  id UUID,
  email TEXT PRIMARY KEY
);

查看表数据

cqlsh:contacts> SELECT * FROM contact;

 email | id
-------+----

(0 rows)

Java客户端

引入依赖

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

连接到Cassandra并插入数据

Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect("contacts");
String insert = "INSERT INTO contact (id, email) " +
        "VALUES (" +
        "bd297650-2885-11e4-8c21-0800200c9a66," +
        "'contact@example.com' " +
        ");";
session.execute(insert);

查看表数据

cqlsh:contacts> SELECT * FROM contact;

 email               | id
---------------------+--------------------------------------
 contact@example.com | bd297650-2885-11e4-8c21-0800200c9a66

(1 rows)

(转载本站文章请注明作者和出处乱世浮生,请勿用于任何商业用途)

comments powered by Disqus