forked from asyncapi/saunter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMessaging.cs
63 lines (53 loc) · 1.98 KB
/
Messaging.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
using System;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Saunter.Attributes;
namespace StreetlightsAPI
{
public class LightMeasuredEvent
{
/// <summary>
/// Id of the streetlight.
/// </summary>
public int Id { get; set; }
/// <summary>
/// Light intensity measured in lumens.
/// </summary>
public int Lumens { get; set; }
/// <summary>
/// Light intensity measured in lumens.
/// </summary>
public DateTime SentAt { get; set; }
}
public interface IStreetlightMessageBus
{
void PublishLightMeasuredEvent(Streetlight streetlight, int lumens);
}
[AsyncApi]
public class StreetlightMessageBus : IStreetlightMessageBus
{
private const string LightMeasuredTopic = "light/measured";
private readonly ILogger _logger;
public StreetlightMessageBus(ILoggerFactory logger)
{
_logger = logger.CreateLogger("Streetlight");
}
[Channel(LightMeasuredTopic)]
[PublishOperation(typeof(LightMeasuredEvent), Summary = "Inform about environmental lighting conditions for a particular streetlight.")]
public void PublishLightMeasuredEvent(Streetlight streetlight, int lumens)
{
var lightMeasuredEvent = new LightMeasuredEvent
{
Id = streetlight.Id,
Lumens = lumens,
SentAt = DateTime.Now,
};
var payload = JsonConvert.SerializeObject(lightMeasuredEvent);
// Simulate publishing a message to the channel.
// In reality this would call some kind of pub/sub client library and publish.
// e.g. mqttClient.PublishAsync(message);
// e.g. amqpClient.BasicPublish(LightMeasuredTopic, routingKey, props, payloadBytes);
_logger.LogInformation("Publishing message {Payload} to {Topic}", payload, LightMeasuredTopic);
}
}
}