-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProducer.cs
108 lines (98 loc) · 2.57 KB
/
Producer.cs
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System.Collections.Generic;
using System.Text;
using System.Windows;
using Confluent.Kafka;
using System;
using NLog;
using NLog.Fluent;
namespace KafkaSniffer
{
class Producer : BrokerInfo
{
private string _topic = "", _key = "";
private bool _notInit = true;
private IProducer<string, string> _producer;
private static Logger Logger = LogManager.GetLogger("producer");
~Producer()
{
Close();
}
public string Topic
{
get { return _topic; }
set
{
_topic = value;
OnPropertyChanged("Topic");
}
}
public string Key
{
get { return _key; }
set
{
_key = value;
OnPropertyChanged("Key");
}
}
public string Message { get; set; } = "";
public bool NotInit
{
get { return _notInit; }
set
{
_notInit = value;
OnPropertyChanged("NotInit");
}
}
private void Init()
{
if (!NotInit)
{
return;
}
var brokerList = Endpoint;
var config = new ProducerConfig
{
BootstrapServers = brokerList,
ApiVersionRequest = true,
};
if (Debug)
{
config.Debug = "msg,broker,topic,protocol";
}
_producer = new ProducerBuilder<string, string>(config).SetLogHandler((_, msg) =>
{
Logger.Log(MapLogLevel(msg.Level), msg.Message);
}).Build();
NotInit = false;
}
public void Close()
{
if (!NotInit)
{
_producer.Dispose();
_producer = null;
}
NotInit = true;
}
public async void ProduceMessage()
{
Init();
try
{
var result = await _producer.ProduceAsync(_topic
, new Message<string, string>
{
Key = Key,
Value = Message,
});
MessageBox.Show($"Send message to [{_topic}] success.");
}
catch (ProduceException<string, string> e)
{
MessageBox.Show($"Send message to [{_topic}] fail. Error:[{e.Error.Reason}]");
}
}
}
}