-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRabbitReceiver.cs
More file actions
102 lines (83 loc) · 3 KB
/
RabbitReceiver.cs
File metadata and controls
102 lines (83 loc) · 3 KB
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
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using CarFleetManager;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Newtonsoft.Json;
namespace CarFleetManager
{
public class RabbitReceiver : BackgroundService
{
private IModel _channel;
private IConnection _connection;
public static double lastValue = 0.0;
public RabbitReceiver()
{
// System.Console.WriteLine("RabbitReceiver()");
InitializeRabbitMqListener();
}
private void InitializeRabbitMqListener()
{
var factory = new ConnectionFactory
{
HostName = "rabbitmq",
UserName = "guest",
Password = "guest"
};
Thread.Sleep(10000);
_connection = factory.CreateConnection();
_connection.ConnectionShutdown += RabbitMQ_ConnectionShutdown;
_channel = _connection.CreateModel();
_channel.QueueDeclare(queue: "test_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
stoppingToken.ThrowIfCancellationRequested();
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (ch, ea) =>
{
var content = Encoding.UTF8.GetString(ea.Body.ToArray());
// System.Console.WriteLine(content);
var data = JsonConvert.DeserializeObject<SensorDataModel>(content);
// System.Console.WriteLine($"Speed: {data?.Value}");
HandleMessage(data);
lastValue = data.Value;
_channel.BasicAck(ea.DeliveryTag, false);
};
consumer.Shutdown += OnConsumerShutdown;
consumer.Registered += OnConsumerRegistered;
consumer.Unregistered += OnConsumerUnregistered;
consumer.ConsumerCancelled += OnConsumerCancelled;
_channel.BasicConsume("test_queue", false, consumer);
return Task.CompletedTask;
}
private void HandleMessage(SensorDataModel data)
{
// _customerNameUpdateService.UpdateSensor(data);
}
private void OnConsumerCancelled(object sender, ConsumerEventArgs e)
{
}
private void OnConsumerUnregistered(object sender, ConsumerEventArgs e)
{
}
private void OnConsumerRegistered(object sender, ConsumerEventArgs e)
{
}
private void OnConsumerShutdown(object sender, ShutdownEventArgs e)
{
}
private void RabbitMQ_ConnectionShutdown(object sender, ShutdownEventArgs e)
{
}
public override void Dispose()
{
_channel.Close();
_connection.Close();
base.Dispose();
}
}
}