python工程,kafka消息对接转换成配置文件并完成类似看门狗监控linux系统进程,定期清理日志
wangrong
2025-04-05 88f9100edcba9581214c1a0acc23cd33a821a9c6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import os
from kafka import KafkaConsumer
import configparser
 
# 配置文件路径
config_file = os.path.join(os.getcwd(), 'msg_config.ini')
 
# 读取配置文件
config = configparser.ConfigParser()
config.read(config_file)
 
# 从配置文件中获取 Kafka 参数和输出文件路径
KAFKA_SERVER = config['KAFKA']['server']
TOPIC = config['KAFKA']['topics'].split(', ')
output_file = os.path.join(os.getcwd(), config['OUTPUT']['file'])
 
print(f"Kafka 服务器地址: {KAFKA_SERVER}")
print(f"消费的主题: {TOPIC}")
print(f"输出文件路径: {output_file}")
 
# 创建 KafkaConsumer 实例
consumer = KafkaConsumer(
    *TOPIC,
    bootstrap_servers=[KAFKA_SERVER],
    group_id='test_group', 
    value_deserializer=lambda x: x.decode('utf-8')
)
 
# 打开文件以追加写入
with open(output_file, 'a', encoding='utf-8') as f:
    for message in consumer:
        topic = message.topic
        value = message.value
 
        f.write(f"Topic: {topic}, Message: {value}\n")
        f.flush()
 
        print(f"接收到消息: Topic: {topic}, Message: {value}")