简体   繁体   English

使用数据库的多线程程序的架构

[英]Architechture of multi-threaded program using database

I've got a fairly simple Python program as outlined below: 我有一个相当简单的Python程序,如下所示:

It has 2 threads plus the main thread. 它有2个线程加上主线程。 One of the threads collects some data and puts it on a Queue. 其中一个线程收集一些数据并将其放入队列。

The second thread takes stuff off the queue and logs it. 第二个线程将内容从队列中移出并记录下来。 Right now it's just printing out the stuff from the queue, but I'm working on adding it to a local MySQL database. 现在,它只是从队列中打印出内容,但我正在努力将其添加到本地MySQL数据库中。

This is a process that needs to run for a long time (at least a few months). 此过程需要长时间(至少几个月)运行。

How should I deal with the database connection? 我应该如何处理数据库连接? Create it in main, then pass it to the logging thread, or create it directly in the logging thread? 在main中创建它,然后将其传递到日志记录线程,还是直接在日志记录线程中创建它? And how do I handle unexpected situations with the DB connection (interrupted, MySQL server crashes, etc) in a robust manner? 以及如何以健壮的方式处理数据库连接中的意外情况(中断,MySQL服务器崩溃等)?

How should I deal with the database connection? 我应该如何处理数据库连接? Create it in main, then pass it to the logging thread, or create it directly in the logging thread? 在main中创建它,然后将其传递到日志记录线程,还是直接在日志记录线程中创建它?

I would perhaps configure your logging component with the class that creates the connection and let your logging component request it. 我也许会使用创建连接的类来配置您的日志记录组件,然后让您的日志记录组件请求它。 This is called dependency injection , and makes life easier in terms of testing eg you can mock this out later. 这就是所谓的依赖注入 ,它使测试变得更轻松,例如您可以稍后进行模拟。

If the logging component created the connections itself, then testing the logging component in a standalone fashion would be difficult. 如果日志记录组件自己创建了连接,那么以独立方式测试日志记录组件将很困难。 By injecting a component that handles these, you can make a mock that returns dummies upon request, or one that provides connection pooling (and so on). 通过注入一个处理这些问题的组件,您可以制作一个可以根据请求返回假人的模拟程序,也可以提供一个提供连接池的模拟程序(依此类推)。

How you handle database issues robustly depends upon what you want to happen. 如何有效地处理数据库问题取决于您要发生的事情。 Firstly make your database interactions transactional (and consequently atomic). 首先,使您的数据库交互具有事务性(因此是原子性的)。 Now, do you want your logger component to bring your system to a halt whilst it retries a write. 现在,您是否希望记录器组件在重试写入时停止系统。 Do you want it to buffer writes up and try out-of-band (ie on another thread) ? 您是否希望它缓冲写入并尝试带外(即在另一个线程上)? Is it mission critical to write this or can you afford to lose data (eg abandon a bad write). 编写此文件是否是关键任务,还是您可以承受丢失数据的损失(例如,放弃错误的写操作)。 I've not provided any specific answers here, since there are so many options depending upon your requirements. 我这里没有提供任何具体的答案,因为根据您的要求有很多选择。 The above details a few possible options. 上面详细介绍了一些可能的选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM