如何使用Python代码连接到Cassandra数据库



我遵循了中给出的步骤https://docs.datastax.com/en/developer/python-driver/3.25/getting_started/使用python代码连接到cassandra数据库,但在运行代码片段后,我仍然得到

NoHostAvailable: ('Unable to connect to any servers', {'hosts"port': OperationTimedOut('errors=None, last_host=None'),
  • Python版本2.7和3(为这两个版本都设置了类路径(
  • Java 1.8(类路径已设置(
  • Apache cassandra 3.11.6(已设置Apache home类路径(

我倾向于使用一个非常简单的应用程序来测试与Cassandra集群的连接:

from cassandra.cluster import Cluster
cluster = Cluster(['10.1.2.3'], port=45678)
session = cluster.connect()
row = session.execute("SELECT release_version FROM system.local").one()
if row:
print(row[0])

然后运行它:

$ python HelloCassandra.py
4.0.6

在您的评论中,您提到您得到了OperationTimedOut,这表明驱动程序在客户端超时期内从未从节点得到响应。这通常意味着(a(你连接到了错误的IP,(b(你连接了错误的CQL端口,或者(c(你的应用程序和集群之间存在网络连接问题。

确保您使用的是在cassandra.yamlrpc_address中设置的IP地址。还要确保节点在正确的端口上侦听CQL客户端。您可以通过检查netstatlsof等Linux实用程序的输出来轻松验证这一点,例如:

$ sudo lsof -nPi -sTCP:LISTEN

干杯!

因此,错误消息表明主机/端口组合上没有运行Cassandra,或者负载过重,无法响应。

你能编辑你的问题,将Cassandra连接部分包括在你的代码中,以及你是如何调用它的吗?我有一个我使用的测试脚本(欢迎您查看(,这里是连接部分:

protocol=4
hostname=sys.argv[1]
username=sys.argv[2]
password=sys.argv[3]
nodes = []
nodes.append(hostname)
auth_provider = PlainTextAuthProvider(username=username, password=password)
cluster = Cluster(nodes,auth_provider=auth_provider, protocol_version=protocol)
session = cluster.connect()

我这样称呼它:

$ python3 testCassandra.py 127.0.0.1 aaron notReallyMyPassword
local

你也可以尝试一件事,那就是在集群上运行nodetool status,以确保它运行正常

编辑

local variable 'session' referenced before assignment

在我看来,这听起来像是在session = cluster.connect()之前尝试session.execute。请查看我的Git repo(上面链接(,以查看实例化session的正确顺序。

我没有使用默认端口

在这种情况下,请确保在集群定义中设置了port。例如:

port = 19099
cluster = Cluster(nodes,auth_provider=auth_provider, port=port)

最新更新