Cassandra 数据库介绍

发布时间: 更新时间: 总字数:1025 阅读时间:3m 作者: IP上海 分享 网址

Cassandra是一个混合型的非关系的数据库,类似于Google的BigTable。其主要功能比Dynamo (分布式的Key-Value存储系统)更丰富,最初由Facebook开发并贡献给apache

介绍

  • Cassandra 是一款 Open Source NoSQL Database,用来管理海量数据,速度快,而不会丢数据。
  • 使用场景
    • 互联网类应用,如日志、消息、feed流、订单、账单、网站等
    • 多活
    • 写密集、统计和分析型工作
    • 数据驱动的业务
  • 核心概念
    • CQL(Cassandra Query Language) 是 cassandra 中提供的一种类 SQL 查询语言
    • 数据中心(Data Center, DC) 是指在同一地域下,电力、网络隔离的一组节点
      • 在多DC的部署架构下面,DC之间内网互通,同一DC内网络延时更小,不同DC之间故障隔离
    • Partitioner 用来确定将数据均衡分布在节点上的策略
      • 云数据库 Cassandra 中,默认使用 Murmur3Partitioner
    • 副本数(Replication factor) 表示数据在集群中存几副本
      • 例如:副本数为 2 表示每行数据在集群中保存了两个副本,每个副本都在不同的节点上面
      • 云数据库Cassandra中,副本数由用户在创建 keyspace 时指定
    • 副本策略(Replica placement strategy) 用来确定将副本存放在哪个节点上面
      • 云数据库 Cassandra 中,副本策略由用户在创建 keyspace 时指定
      • 推荐您使用 NetworkTopologyStrategy 策略,可更便捷地将集群扩展至多个DC
    • KeySpace:一个 KeySpace 下包含若干个表,用户可以在 keyspce 这个级别指定副本策略
    • Cluster 一个集群包含一个或多个数据中心
    • SSTable(Sorted String Table) 一个 SSTable 是一个不可变的数据文件,Cassandra 定期将 memtables 写入其中
    • 提交日志(Commit log) 为了持久性,所有数据写入之前都要首先写入提交日志(日志写入优先)
      • 所有数据都刷新到SSTables之后,就可以对其进行归档、删除或回收
    • CQL Table 按表行获取的有序列的集合
      • 一张表由多列组成,并且有一个主键
    • Node 存储数据的节点
    • snitch 将一组机器定义为数据中心和机架(拓扑),副本策略使用这些数据中心和机架放置副本

部署

常用端口

  • 7199 JMX(8080 pre Cassandra 0.8.xx)
  • 7000 节点间通信(非 TLS)
  • 7001 TLS 节点间通信
  • 9160 Thrift 客户端 API
  • 9042 CQL 本地传输端口

使用 Docker 安装 Cassandra

docker pull cassandra:latest

docker network create cassandra

docker run --rm -d --name cassandra --hostname cassandra --network cassandra cassandra

CQL

Cassandra 查询语言 (CQL) 与 SQL 非常相似,但适合 Cassandra 的无 JOIN 结构。

  • data.cql
-- Create a keyspace
CREATE KEYSPACE IF NOT EXISTS store WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : '1' };

-- Create a table
CREATE TABLE IF NOT EXISTS store.shopping_cart (
userid text PRIMARY KEY,
item_count int,
last_update_timestamp timestamp
);

-- Insert some data
INSERT INTO store.shopping_cart
(userid, item_count, last_update_timestamp)
VALUES ('9876', 2, toTimeStamp(now()));
INSERT INTO store.shopping_cart
(userid, item_count, last_update_timestamp)
VALUES ('1234', 5, toTimeStamp(now()));
  • data.cql 加载数据到 Cassandra
docker run --rm --network cassandra -v "$(pwd)/data.cql:/scripts/data.cql" -e CQLSH_HOST=cassandra -e CQLSH_PORT=9042 -e CQLVERSION=3.4.6 nuvo/docker-cqlsh
  • 交互式 CQLSH
$ docker run --rm -it --network cassandra nuvo/docker-cqlsh cqlsh cassandra 9042 --cqlversion='3.4.5'
Connected to Test Cluster at cassandra:9042.
[cqlsh 5.0.1 | Cassandra 4.0.4 | CQL spec 3.4.5 | Native protocol v5]
Use HELP for help.
cqlsh>
  • 简单使用
# 查
SELECT * FROM store.shopping_cart;

# 写
INSERT INTO store.shopping_cart (userid, item_count) VALUES ('4567', 20);

参考

  1. https://cassandra.apache.org/
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数