Kafka生产者和使用者脚本自动运行

时间:2018-11-01 09:20:01

标签: python django apache-kafka

我有一个Django项目,正在使用pykafka。我在项目内部创建了两个名为producer.py和Consumer.py的文件。我必须将目录更改为存在这些文件夹的文件夹,然后从终端分别运行python producer.py和consumer.py。一切正常。

我在线部署了项目,并且Web应用程序正在运行,因此我想在后台自动运行生产者和使用者。我该怎么办?

编辑1:在生产服务器上,我执行了nohup python name_of_python_script.py &在后​​台执行它。这暂时有效,但这是一个好的解决方案吗?

1 个答案:

答案 0 :(得分:0)

您可以在MyKafkaConsumer.service下创建具有以下内容的系统服务/etc/systemd/system

[Unit]
Description=A Kafka Consumer written in Python
After=network.target # include any other pre-requisites 

[Service]
Type=simple
User=your_user
Group=your_user_group
WorkingDirectory=/path/to/your/consumer
ExecStart=python consumer.py
TimeoutStopSec=180
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target 

为了启动服务(并配置它以便在启动时运行),您应该运行

systemctl enable MyKafkaConsumer.service
systemctl start MyKafkaConsumer.service

要检查其状态:

systemctl status MyKafkaConsumer

并查看日志:

journactl -u MyKafkaConsumer -f

(或者,如果您想查看最后100行)

journalctl -u MyKafkaConsumer -n 100

您还需要为生产者创建类似的服务。

系统服务有很多选择。如果您需要任何进一步的说明,可以参考this article。不过,在网上不难找到指南和其他材料。

相关问题