Skip to content

Latest commit

 

History

History
59 lines (48 loc) · 2.31 KB

File metadata and controls

59 lines (48 loc) · 2.31 KB

Example Worker

This project makes use of the RabbitExpress.QueueClient and utilizes the RabbitExpress.Serializers.JsonSerializer when communicating with the queue.

Add the reference

In the csproj add a PackageReference to the RabbitExpress.Serializers.JsonSerializer

<ItemGroup>
    <PackageReference Include="RabbitExpress.Serializers.JsonSerializer" Version="1.*" />
</ItemGroup>

or the RabbitExpress.Serializers.MsgPackSerializer package.

<ItemGroup>
    <PackageReference Include="RabbitExpress.Serializers.MsgPackSerializer" Version="1.*" />
</ItemGroup>

A simple worker

The main code makes use of predefined messages and queues. See RabbitExpress.Example.Shared for details.

Making use of the the worker is a little more involved than using the client for publishing.

var r = new Random();
using (var qc = new QueueClient<JsonSerializer>(new Uri(config["RabbitExpressConnection"])))
{
    qc.RegisterWorker<Queues, ExampleMessage>(Queues.EXAMPLE_QUEUE, m =>
    {
        try
        {
            if (string.IsNullOrWhiteSpace(m.Message?.Text))
            {
                Console.WriteLine("Rejecting empty message.");
                return WorkerResult.Failed;
            }

            if (r.Next(100) % 3 == 0)
            {
                throw new ApplicationException("Simulated recoverable error.");
            }

            Console.WriteLine($"Acknowledging {m.Message.Text}");
            return WorkerResult.Success;
        }
        catch (Exception e)
        {
            Console.WriteLine($"Rejecting {m.Message?.Text} with reason: {e}");
            return WorkerResult.Requeue;
        }
    });
    Console.ReadLine();
}

This simple code will continuously wait for an ExampleMessage on the RabbitMQ queue called EXAMPLE_QUEUE. The most important part is gc.WatchQueue<ExampleMessage>(Queues.<QueueName>, ...);. The delegate passed to this function will be called for every valid received message.