コード例 #1
0
        public void Init(string domain)
        {
            var exchangeName = GetTopicName();
            var queueName    = GetQueueName(domain);

            for (var i = 0; i < GetConsumersCount(); i++)
            {
                var channelName = $"{queueName}_{Thread.CurrentThread.ManagedThreadId}+{i}";

                RabbitHelper.GetRabbitChannel(channelName).ExchangeDeclare(exchangeName, ExchangeType.Topic, true, false);
                RabbitHelper.GetRabbitChannel(channelName).QueueDeclare(queueName, true, false, false, null);
                RabbitHelper.GetRabbitChannel(channelName).QueueBind(queueName, exchangeName, GetRoutingKey(), null);

                var consumer = new AsyncEventingBasicConsumer(RabbitHelper.GetRabbitChannel(channelName));
                consumer.Received += async(ch, ea) =>
                {
                    var body    = System.Text.Encoding.UTF8.GetString(ea.Body.ToArray());
                    T   payload = JsonSerializer.Deserialize <T>(body, _jsonSerializerOptions);
                    Process(payload);
                    RabbitHelper.GetRabbitChannel(channelName).BasicAck(ea.DeliveryTag, false);
                    await Task.Yield();
                };
                RabbitHelper.GetRabbitChannel(channelName).BasicConsume(queueName, false, consumer);
                _consumers.Add(consumer);
            }
        }
コード例 #2
0
        public void Publish(T payload)
        {
            var classNames   = Regex.Split(payload.GetType().Name, @"(?<!^)(?=[A-Z])");
            var exchangeName = $"TOPIC/{classNames[0].ToUpper()}";
            var routeKey     = $"{classNames[0].ToLower()}.{classNames[1].ToLower()}.{payload.Id}";
            var payloadBody  = System.Text.Encoding.UTF8.GetBytes(JsonSerializer.Serialize(payload, _jsonSerializerOptions));

            RabbitHelper.GetRabbitChannel(exchangeName).ExchangeDeclare(exchangeName, ExchangeType.Topic, true, false);
            RabbitHelper.GetRabbitChannel(exchangeName).BasicPublish(exchangeName, routeKey, null, payloadBody);
        }