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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import json
import time
import configparser
from kafka import KafkaProducer
from threading import Timer
 
# 读取配置文件
def load_config(config_file):
    config = configparser.ConfigParser()
    config.read(config_file)
    return config
 
# 读取 JSON 文件内容
def load_json(json_file):
    with open(json_file, 'r') as f:
        return json.load(f)
 
# 发送消息到 Kafka
def send_message(producer, topic, message):
    producer.send(topic, value=json.dumps(message).encode('utf-8'))
    print(f"Sent message to {topic}: {message}")
 
# 定时发送消息
def send_periodically(producer, topic, message, interval, stop_flag):
    if stop_flag[0]:  # 如果 stop_flag 是 True,则停止发送
        send_message(producer, topic, message)
        # 设置定时器,按照给定的间隔继续发送
        Timer(interval, send_periodically, [producer, topic, message, interval, stop_flag]).start()
    else:
        print("Stopping periodic message sending.")
 
# 停止定时器
def stop_sending(stop_flag):
    stop_flag[0] = False
    print("Message sending stopped.")
 
def main():
    # 配置文件路径
    config_file = 'msg_config.ini'
    config = load_config(config_file)
 
    # Kafka 配置
    kafka_server = config['KAFKA']['server']
    topics = config['KAFKA']['topics'].split(',')  # topics 列表
    send_topics = config['SEND_MSG']['send_topics']
    run_send = config.getboolean('SEND_MSG', 'run_send')  # run_send 为布尔值
    send_interval = config.getint('SEND_MSG', 'send_interval')
    json_file = config['SEND_MSG']['json_file']
 
    # 读取消息内容
    message = load_json(json_file)
 
    # 创建 Kafka producer
    producer = KafkaProducer(bootstrap_servers=kafka_server)
 
    # 如果需要发送消息,则启动定时任务
    if run_send:
        print(f"Sending messages to {send_topics} every {send_interval} seconds...")
        
        # 使用列表来实现可修改的标志位
        stop_flag = [True]
        
        # 启动定时器
        send_periodically(producer, send_topics, message, send_interval, stop_flag)
 
        # 例如,可以在10秒后停止定时发送
        #time.sleep(10)
        #stop_sending(stop_flag)
    else:
        print("run_send is false. No messages will be sent.")
 
if __name__ == "__main__":
    main()