[英]Why does the python Cassandra driver fail when declared as a class field?
我目前正在使用一個服務器進程,該進程旨在連接到Cassandra數據庫並將信息轉發給它。 這個過程是作為一個類編寫的,我的目標是為這個類創建一個可以用來發送信息的Cassandra會話。 但是,我遇到了一個問題; 當我在類init方法中創建一個Cassandra會話,然后嘗試在另一個方法中使用該會話時,我收到以下錯誤: errors={}, last_host=<server IP address>
。 我現在可以通過在每次調用方法時創建一個新的Cassandra會話來解決這個問題,但這顯然不是一個很好的方法來解決這個問題。 那么,我怎樣才能創建一個我可以在整個課程中始終如一地使用的Cassandra會話?
此代碼不起作用:
from cassandra.cluster import Cluster
from multiprocessing import Process
class DataProcess(Process):
def __init__(self):
super(DataProcess,self).__init__()
# Do a few other irrelevant things ...
# Set up the Cassandra connection
self.cluster = Cluster(contact_points=[CASSANDRA_IP])
self.session = self.cluster.connect('some keyspace')
print "Connected to cassandra."
def callback(self,ch,method,props,body):
prepared_statement = self.session.prepare("Some CQL statement...")
bound_statement = prepared_statement.bind(some values)
self.session.execute(bound_statement)
Output:
"Connected to cassandra."
errors={}, last_host=<server IP address>
這段代碼可行,但這是一種愚蠢的方式:
from cassandra.cluster import Cluster
from multiprocessing import Process
class DataProcess(Process):
def __init__(self):
super(DataProcess,self).__init__()
# Do a few irrelevant things ...
def callback(self,ch,method,props,body):
# Set up the Cassandra connection
cluster = Cluster(contact_points=[CASSANDRA_IP])
session = cluster.connect('some keyspace')
prepared_statement = session.prepare("Some CQL statement...")
bound_statement = prepared_statement.bind(some values)
session.execute(bound_statement)
其他相關信息:
使用python cassandra-driver版本2.5.1
Cassandra數據庫版本2.1.8
編輯:答案以下代碼解決了這個問題:
from cassandra.cluster import Cluster
from multiprocessing import Process
class DataProcess(Process):
def __init__(self):
super(DataProcess,self).__init__()
self.cluster = None
self.session = None
# Do a few irrelevant things ...
def callback(self,ch,method,props,body):
# Set up the Cassandra connection
cluster = Cluster(contact_points=[CASSANDRA_IP])
session = cluster.connect('some keyspace')
prepared_statement = session.prepare("Some CQL statement...")
bound_statement = prepared_statement.bind(some values)
session.execute(bound_statement)
def run(self):
self.cluster = Cluster(contact_points=[CASSANDRA_IP])
self.session = self.cluster.connect('some keyspace')
你是在fork之前創建集群和會話嗎? 這可能會導致你所看到的問題。 還有就是如何使用池使用Python司機在這里分配工作驚人的書面記錄在這里 。 這可能正是您正在尋找的。
如果不是,請在運行流程的過程中留下更多背景信息,因為在不了解流程生命周期的情況下很難重現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.