python - 如何将 python 连接到使用 docker 运行的 cassandra

标签 python docker cassandra docker-toolbox

我想要获取在线数据并保存到 cassandra keyspace。我阅读了本指南,https://phoenixnap.com/kb/install-cassandra-on-windows ,运行 Cassandra 。看起来很简单,但是我得到了与 jdk 相关的错误。所以,我尝试了不同的方式。我尝试使用 docker-toolbox (Windows 8.1)。我在 docker-toolbox shell 中通过以下步骤运行 cassndra:

$ docker run --name some-cassandra2 --network some-network -d cassandra:latest

$ docker run -it --network some-network --rm cassandra cqlsh some-cassandra2

enter image description here

cqlsh>create keyspace CityInfo with replication = {'class' : 'SimpleStrategy', 'replication_factor':2};

cqlsh>use CityInfo;

cqlsh> CREATE TABLE cities (id int,name text,country text,PRIMARY KEY(id));

cqlsh> CREATE TABLE users (username text,name text,age int,PRIMARY KEY(username));

现在,我想使用 python 代码获取在线数据并保存到城市和用户表中。我获取在线数据。我尝试使用以下代码连接:

from cassandra.cluster import Cluster
cluster = Cluster(['172.18.0.2'],port=9042)
session = cluster.connect('cityinfo',wait_for_all_pools=False)
session.execute('USE cityinfo')
rows = session.execute('SELECT * FROM users')
for row in rows:
        print(row.age,row.name,row.username)

但我看到错误:

File "cassandra\cluster.py", line 3533, in cassandra.cluster.ControlConnection._reconnect_internal

NoHostAvailable: ('Unable to connect to any servers', {'172.18.0.2:9042': OSError(None, "Tried connecting to [('172.18.0.2', 9042)]. Last error: timed out")}) 

我尝试了几种方法。例如,我尝试使用其他 ip sush 作为 127.0.0.1:9042,或者在运行 cassandra 将容器端口连接到设备端口时添加 -p7000:7000。但我不能。 请指导我。有什么问题吗?

最佳答案

我建议从在同一网络上运行的容器运行Python代码,这样你就可以在Python中直接使用容器名称而不是IP地址。我能够毫无问题地运行您的代码,执行以下操作。

我创建了一个运行 Python 的 docker 容器,也在 some-network 上运行。

docker run -it --rm --network some-network python:3.8-slim bash

继续在容器内安装 cassandra-driver。

pip install cassandra-driver

users 表中填充了一些虚拟数据,然后继续打开 Python 终端。

from cassandra.cluster import Cluster
cluster = Cluster(['some-cassandra2'], port=9042)
session = cluster.connect('cityinfo',wait_for_all_pools=False)
session.execute('USE cityinfo')
rows = session.execute('SELECT * FROM users')
for row in rows:
    print(row.age,row.name,row.username)

请注意,与您的代码的唯一区别是这一行我使用容器名称而不是 IP 地址:

cluster = Cluster(['some-cassandra2'], port=9042)

关于python - 如何将 python 连接到使用 docker 运行的 cassandra,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68426835/

相关文章:

python - 实时绘图中的多个数据系列

python - 在已知字符串之前查找任意长度的字符串

docker 用于 com.docker.hyperkit 中的 mac 内存使用情况

docker - 如何删除用于生产和复制的 Docker 卷?

mysql - 从 Cassandra 中提取数据以加载到关系数据库中的机制

python - 在解释性语言中使用匈牙利符号前缀是否有意义?

python - 通过与 Pandas 中的另一个数据框匹配来替换列表列的有效方法

php - 无法从 php 容器连接到 mysql 容器

Cassandra 批量插入解决方案

用于水平压实柱系列的 Cassandra 主要压实