示例#1
0
        static async Task Main(string[] args)
        {
            Customer customer = new()
            {
                Name   = "The Customer",
                Orders = new()
                {
                    new() { Id = "order1" },
                    new() { Id = "order2" },
                }
            };


            ConnectionFactory factory = new()
            {
                //Uri = "amqp://*****:*****@hostName:port/vhost";
                HostName           = "localhost",
                UserName           = "******",
                Password           = "******",
                RequestedHeartbeat = TimeSpan.FromSeconds(15),
            };

            const string exchange    = "test_exchange";
            const string queuePrefix = "test_queue_";
            const string routingKey  = "test.message";

            using var sub1 = (await RabbitMqSubscriber.CreateAsync(factory, new() { Exchange = exchange, Queue = queuePrefix + "1", RoutingKey = routingKey }))
                             .Subscribe((bytes, isRedelivered) =>
            {
                string message;
                Customer customer;
                if (bytes.Length < 20)
                {
                    message = Encoding.UTF8.GetString(bytes);
                }
                else
                {
                    customer = Deserialize <Customer>(bytes);
                    message  = customer.Name;
                }

                Console.WriteLine($"1 -> {message}");
            });

            using var sub2 = (await RabbitMqSubscriber.CreateAsync(factory, new() { Exchange = exchange, Queue = queuePrefix + "2", RoutingKey = routingKey }))
                             .Subscribe((bytes, isRedelivered) => Handler(bytes, isRedelivered));

            using var pub = await RabbitMqPublisher.CreateAsync(factory, new() { Exchange = exchange, RoutingKey = routingKey });

            var count = 1;

            while (true)
            {
                try
                {
                    if (await pub.PublishAsync(Encoding.UTF8.GetBytes($"Message {count}")) &&
                        await pub.PublishAsync(Serialize(customer)))
                    {
                        count++;
                    }
                }
                catch (Exception e)
                {
                }

                Thread.Sleep(5000);
            }

            //Console.ReadKey();
        }