|
| 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 | + switch (pr.Outcome.State) |
| 31 | + { |
| 32 | + case OutcomeState.Accepted: |
| 33 | + break; |
| 34 | + case OutcomeState.Released: |
| 35 | + Console.Error.WriteLine($"Released message: {pr.Message.BodyAsString()}"); |
| 36 | + Environment.Exit(1); |
| 37 | + break; |
| 38 | + case OutcomeState.Rejected: |
| 39 | + Console.Error.WriteLine($"[Publisher] Message: {pr.Message.BodyAsString()} rejected with error: {pr.Outcome.Error}"); |
| 40 | + Environment.Exit(1); |
| 41 | + break; |
| 42 | + default: |
| 43 | + Console.Error.WriteLine($"Unexpected publish outcome: {pr.Outcome.State}"); |
| 44 | + Environment.Exit(1); |
| 45 | + break; |
| 46 | + } |
| 47 | + |
| 48 | + Console.WriteLine($" [x] Sent '{routingKey}':'{message}'"); |
| 49 | + } |
| 50 | + finally |
| 51 | + { |
| 52 | + await publisher.CloseAsync(); |
| 53 | + } |
| 54 | +} |
| 55 | +finally |
| 56 | +{ |
| 57 | + await connection.CloseAsync(); |
| 58 | + await environment.CloseAsync(); |
| 59 | +} |
| 60 | + |
| 61 | +static string GetRouting(string[] strings) => strings.Length < 1 ? "anonymous.info" : strings[0]; |
| 62 | + |
| 63 | +static string GetMessage(string[] strings) |
| 64 | +{ |
| 65 | + if (strings.Length < 2) |
| 66 | + { |
| 67 | + return "Hello World!"; |
| 68 | + } |
| 69 | + |
| 70 | + return string.Join(" ", strings.Skip(1)); |
| 71 | +} |
0 commit comments