Docker快速构建Cassandra和Java操作

搭建Cassandra

使用docker创建Cassandra,方便快捷

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

创建keyspace、table

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#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
);

查看表数据

1
2
3
4
5
6
cqlsh:contacts> SELECT * FROM contact;

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

(0 rows)

Java客户端

引入依赖

1
2
3
4
5
<dependency> 
  <groupId>com.datastax.cassandra</groupId> 
  <artifactId>cassandra-driver-core</artifactId> 
  <version>3.2.0</version> 
</dependency>

连接到Cassandra并插入数据

1
2
3
4
5
6
7
8
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);

查看表数据

1
2
3
4
5
6
7
cqlsh:contacts> SELECT * FROM contact;

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

(1 rows)

Comments

comments powered by Disqus