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

问题描述

我想获取在线数据并保存到 cassandra 密钥空间。我阅读了本指南 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,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)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...