-
Notifications
You must be signed in to change notification settings - Fork 0
/
RabbitMQHelper.cs
88 lines (83 loc) · 2.62 KB
/
RabbitMQHelper.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
using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Text;
using System.Text.Json;
namespace Net6_Demo.Helpers
{
/// <summary>
/// Handle RabbitMQ publish
/// </summary>
public class RabbitMQHelper
{
private readonly IModel _channel;
private readonly string _routeKey;
private readonly string _exchangeId;
public RabbitMQHelper(IOptions<RabbitMQSetting> options)
{
var setting = options.Value;
_routeKey = setting.RoutingKey;
_exchangeId = setting.ExchangeId;
try
{
var factory = new ConnectionFactory()
{
HostName = setting.Host,
UserName = setting.UserName,
Password = setting.Password,
Port = options.Value.RabbitPort,
};
var connection = factory.CreateConnection();
_channel = connection.CreateModel();
}
catch (Exception ex)
{
//TODO
Console.WriteLine(ex.Message);
}
}
/// <summary>
/// Get connection for consumer
/// </summary>
/// <returns></returns>
public IModel GetConnection()
{
return _channel;
}
/// <summary>
/// Publish message
/// </summary>
/// <param name="message"></param>
public void Publish(object message)
{
try
{
var body = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message));
_channel.BasicPublish(exchange: _exchangeId,
routingKey: _routeKey,
basicProperties: null,
body: body);
}
catch (Exception ex)
{
//TODO
Console.WriteLine(ex.Message);
}
}
//just demo
private Task Consume(string queue)
{
var consumer = new EventingBasicConsumer(_channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body.ToArray();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
};
_channel.BasicConsume(queue: queue,
autoAck: true,
consumer: consumer);
return Task.CompletedTask;
}
}
}