【问题标题】:python3 nameko RPC server with mysql connectionpython3 nameko RPC服务器与mysql连接
【发布时间】:2018-06-20 08:53:10
【问题描述】:

我尝试使用 nameko rpc 服务器从 mysql 读取数据。这是服务器代码。

class SendService:
    name = 'url_feature_rpc_service'
    def __init__(self):
        print('new connection')
        self.db = MySQLdb.connect(host="localhost", user="user", passwd="123456", db="today_news", charset='utf8')
        self.cursor = self.db.cursor()

    @rpc
    def get_feature(self, url):
        sql = 'select title_seg, entity_seg, title_entity_vec from article_feature where url_md5 = md5(\'{}\')'.format(url)
        self.cursor.execute(sql)
        result = self.cursor.fetchone()
        if result == None:
            return ''
        return '\t'.join(result)

这是客户端代码:

with ClusterRpcProxy(config) as cluster_rpc:
    for line in sys.stdin:
        line = line.strip()
        try:
            result = cluster_rpc.url_feature_rpc_service.get_feature(line)
        except Exception as e:
            print(e)

我的问题是每次我调用 rpc 服务时,它都会建立一个新的连接。我有时会收到 mysql 错误(99)“无法连接 mysql 服务器”。我可以只使用一个连接吗?

【问题讨论】:

  • 您没有包含异常消息
  • @DashWinterson,对不起,我不能不上传照片。异常消息是“OperationalError(2003, “Can't connect to MySQL server on 'mysql.server' (99)”

标签: python mysql python-3.x nameko


【解决方案1】:

您应该使用像 nameko-sqlalchemy 这样的 DependencyProvider 来连接到数据库。

__init__ 中实例化 MySQL 连接意味着您将在每次 RPC 方法触发时创建一个新连接,这可能意味着您的连接用完了。

【讨论】:

  • 谢谢,您只是指出了问题所在。我不知道如何使用 DependencyProvider,但是我将 db 和 cursor 更改为类中的统计变量并使用 SendService.cursor 在 func get_feature 中执行 sql 刚刚解决了这个问题。这样可以吗?
  • 这绝对不是正确的做法,而且可能会有意想不到的副作用。阅读nameko.readthedocs.io/en/stable/… 了解我们为什么使用依赖注入模式。
【解决方案2】:

您有挂起的数据库连接,您需要在请求结束时关闭()数据库。

@rpc
def get_feature(self, url):
    sql = 'select title_seg, entity_seg, title_entity_vec from article_feature where url_md5 = md5(\'{}\')'.format(url)
    self.cursor.execute(sql)
    result = self.cursor.fetchone()
    self.db.close()
    if result == None:
        return ''
    return '\t'.join(result)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多