将WCF服务订阅到RabbitMQ

时间:2019-01-30 11:22:20

标签: c# wcf iis rabbitmq

我想将WCF服务订阅RabbitMQ队列,以简单地利用IIS的优势进行扩展,该IIS关心线程,进程ecc。 我尝试像这样在Application_Start方法中在Global.asax中预订WCF:

    protected void Application_Start(object sender, EventArgs e)
    {
        var factory = new ConnectionFactory
        {
            HostName = "hostname",
            Port = 5672,
            UserName = "username",
            Password = "password"
        };

        ServiceResponse response = null;

        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "identity_provider", durable: false, exclusive: false, autoDelete: false,
                    arguments: null);

                channel.BasicQos(0, 1, false);

                var consumer = new EventingBasicConsumer(channel);

                channel.BasicConsume(queue: "identity_provider", autoAck: false, consumer: consumer);

                consumer.Received += (model, ea) =>
                {

                    var head = CreateHead(ea.BasicProperties.Headers);
                    var body = ea.Body;
                    var props = ea.BasicProperties;
                    var replyProps = channel.CreateBasicProperties();
                    replyProps.CorrelationId = props.CorrelationId;

                    try
                    {
                        var message = Encoding.UTF8.GetString(body);

                        response = new IdentityProviderService().Execute(head, message);
                    }
                    catch (Exception ex)
                    {
                        response = new ServiceResponse
                        {
                            Message = ex.Message
                        };
                    }
                    finally
                    {
                        var responseBytes = Encoding.UTF8.GetBytes(response.Message);
                        channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: replyProps,
                            body: responseBytes);
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    }
                };
            }
        }
    }

    private static Head CreateHead(IDictionary<string, object> headDictionary)
    {

        return new Head
        {

            User = Encoding.UTF8.GetString((byte[])headDictionary["user"]),
        };
    }

但是它不起作用。有办法解决这个问题吗? 我可以使用Windows服务根据队列中的消息打开更多任务吗?怎么样? 谢谢。

0 个答案:

没有答案