|
| 1 | +using System.Text; |
| 2 | +using RabbitMQ.AMQP.Client; |
| 3 | +using RabbitMQ.AMQP.Client.Impl; |
| 4 | + |
| 5 | +const string brokerUri = "amqp://guest:guest@localhost:5672/%2f"; |
| 6 | +const string exchangeName = "logs_topic"; |
| 7 | + |
| 8 | +string routingKey = GetRouting(args); |
| 9 | +string message = GetMessage(args); |
| 10 | + |
| 11 | +ConnectionSettings settings = ConnectionSettingsBuilder.Create() |
| 12 | + .Uri(new Uri(brokerUri)) |
| 13 | + .ContainerId("tutorial-emitlogtopic") |
| 14 | + .Build(); |
| 15 | + |
| 16 | +IEnvironment environment = AmqpEnvironment.Create(settings); |
| 17 | +IConnection connection = await environment.CreateConnectionAsync(); |
| 18 | + |
| 19 | +try |
| 20 | +{ |
| 21 | + IManagement management = connection.Management(); |
| 22 | + IExchangeSpecification exchangeSpec = management.Exchange(exchangeName).Type("topic"); |
| 23 | + await exchangeSpec.DeclareAsync(); |
| 24 | + |
| 25 | + IPublisher publisher = await connection.PublisherBuilder().Exchange(exchangeName).Key(routingKey).BuildAsync(); |
| 26 | + try |
| 27 | + { |
| 28 | + var amqpMessage = new AmqpMessage(Encoding.UTF8.GetBytes(message)); |
| 29 | + PublishResult pr = await publisher.PublishAsync(amqpMessage); |
| 30 | + if (pr.Outcome.State != OutcomeState.Accepted) |
| 31 | + { |
| 32 | + Console.Error.WriteLine($"Unexpected publish outcome: {pr.Outcome.State}"); |
| 33 | + Environment.Exit(1); |
| 34 | + } |
| 35 | + |
| 36 | + Console.WriteLine($" [x] Sent '{routingKey}':'{message}'"); |
| 37 | + } |
| 38 | + finally |
| 39 | + { |
| 40 | + await publisher.CloseAsync(); |
| 41 | + } |
| 42 | +} |
| 43 | +finally |
| 44 | +{ |
| 45 | + await connection.CloseAsync(); |
| 46 | + await environment.CloseAsync(); |
| 47 | +} |
| 48 | + |
| 49 | +static string GetRouting(string[] strings) => strings.Length < 1 ? "anonymous.info" : strings[0]; |
| 50 | + |
| 51 | +static string GetMessage(string[] strings) |
| 52 | +{ |
| 53 | + if (strings.Length < 2) |
| 54 | + { |
| 55 | + return "Hello World!"; |
| 56 | + } |
| 57 | + |
| 58 | + return string.Join(" ", strings.Skip(1)); |
| 59 | +} |
0 commit comments