如何在WCF中使用RabbitMQ?

时间:2017-09-06 09:19:15

标签: c# wcf rabbitmq wcf-binding

我有一个scenerio,其中可执行文件是生产者,WCF服务是消费者。

WCF服务WorkFlow如下:

1)Service调用可执行文件(producer),这个可执行文件是另一个将消息生成RabbitMQ Queue的过程。

2)服务必须使用来自RabbitMQ队列的消息

3)将数据返回给客户端。

using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace ConnectionServices
{

    public class Connection : IConnection
    {
        public string ConnectSite(string provider, string server, string siteName)
        {
            InvokeProducer(provider, server, siteName);
            string activeInstance = RunRabbitMQ();
            return activeInstance;

        }
        public void InvokeProducer(string provider, string server, string siteName)
        {
            string siteManagerExePath = @"C:\Users\mbmercha\Documents\Visual Studio 2015\Projects\Producer\Producer\bin\Debug\Producer.exe";
            try
            {
                ProcessStartInfo startInfo = new ProcessStartInfo();
                Process siteManagerProcess = new Process();
                startInfo.FileName = siteManagerExePath;
                startInfo.Arguments = string.Format("{0} {1} {2} {3}", "-b ", provider, server, siteName);
                siteManagerProcess.StartInfo = startInfo;
                siteManagerProcess.Start();
                siteManagerProcess.WaitForExit();

            }
            catch (Exception e)
            {

            }
        }
        public string RunRabbitMQ()
        {
            var factory = new ConnectionFactory() { HostName = "localhost" };
            string activeInstance = null;
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare("DurableQueue", true, false, false, null);
                channel.ExchangeDeclare("DurableExchange", ExchangeType.Topic, true);
                channel.QueueBind("DurableQueue", "DurableExchange", "durable");
                var consumer = new EventingBasicConsumer(channel);

                consumer.Received += (model, ea) =>
                {
                    var body = ea.Body;
                    var message = Encoding.UTF8.GetString(body);
                    activeInstance = message;
                };
                channel.BasicConsume(queue: "DurableQueue",
                                     autoAck: false,
                                     consumer: consumer);


            }
            return activeInstance;
        }
    }
}

到目前为止,服务能够调用可执行文件并在队列中生成消息。

但是服务从第2步失败,它返回null而不是实际消息。 谁能告诉我这里我缺少的东西?

先谢谢。

1 个答案:

答案 0 :(得分:2)

您永远不会将activeInstance设置为null以外的任何内容。

您似乎正在使用异步API,这意味着您在RunRabbitMQ方法调用完成后很久就从RabbitMQ中检索消息...或者如果您没有立即处置返回时的所有消费者机器。

如果要同步检索消息 - 在这种情况下,在同步方法调用中 - 您需要等待消息可用。为此,您需要使用'pull API',即channel.BasicGet(...)