You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Python初始化Cassandra集群时遭遇连接错误求助

Cassandra Python连接问题排查

问题详情

我使用以下Python代码初始化Cassandra集群:

cluster = Cluster(['172.31.29.49', '172.31.47.96'])
session = cluster.connect()
create_cassandra_table(session)

最初使用127.0.0.1作为地址时,收到如下错误:

File "/home/ubuntu/snapshot.py", line 125, in <module>
store_docker_checkpoints()
File "/home/ubuntu/snapshot.py", line 94, in store_docker_checkpoints
session = cluster.connect()
File "cassandra/cluster.py", line 1717, in cassandra.cluster.Cluster.connect
File "cassandra/cluster.py", line 1753, in cassandra.cluster.Cluster.connect
File "cassandra/cluster.py", line 1740, in cassandra.cluster.Cluster.connect
File "cassandra/cluster.py", line 3543, in cassandra.cluster.ControlConnection.connect
File "cassandra/cluster.py", line 3588, in cassandra.cluster.ControlConnection._reconnect_internal
cassandra.cluster.NoHostAvailable: ('Unable to connect to any servers', {'127.0.0.1:9042':    ConnectionRefusedError(111, "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

随后我将集群地址更换为两个EC2实例的私有IPv4地址(这是一个双节点集群),执行nodetool status显示集群状态正常,但运行脚本时仍出现错误。

排查建议

  • 检查EC2实例安全组规则,确保9042端口(Cassandra CQL通信端口)对运行脚本的机器开放:若脚本在集群内实例运行,需允许实例间9042端口通信;若在外部机器运行,需添加对应IP的访问权限。
  • 验证Cassandra配置文件cassandra.yaml的关键参数:
    • listen_address需设置为节点私有IP,保证节点间正常通信
    • rpc_address不要仅绑定127.0.0.1,可设为0.0.0.0或节点私有IP,允许外部连接
  • 确认两个节点的Cassandra服务正常运行,执行systemctl status cassandra检查状态
  • 测试端口连通性:从运行脚本的机器执行telnet 172.31.29.49 9042或nc -zv 172.31.29.49 9042,确认9042端口可访问
  • 在Python代码中显式指定端口,避免端口配置错误:
    cluster = Cluster(['172.31.29.49', '172.31.47.96'], port=9042)
    
  • 查看Cassandra日志(默认路径/var/log/cassandra/),排查是否存在端口绑定失败、认证错误等连接相关异常

内容的提问来源于stack exchange,提问作者Yosra Khlifi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 16:22:47