这是我第一次尝试在 stackoverflow 上发布问题。如果问题或方法有问题,请多多包涵。我做了很多搜索以找到我的问题的答案,但无法弄清楚。这就是我想要做的。我编写了一个连接到 RabbitMQ localhost 以检索消息的 WCF 服务。我编写了一个使用 WCF 服务的控制台程序。现在,我希望 WCF 从 RabbitMQ 接收到的任何消息都被传递回控制台程序,而 WCF 仍在等待接收任何即将到来的消息。我看到的示例是使用委托和事件将消息传递回 Windows 窗体应用程序。我很难为控制台程序实现这个。下面是我的 WCF 代码。
public class MessageQueueSvc : IService1
{
public string HOST_NAME = "localhost";
public string EXCHANGE_NAME = "MyExchange";
public string QUEUE_NAME = "MyMessageQ1";
public string ROUTING_KEY = "";
protected bool isConsuming;
public delegate void onReceiveMessage(byte[] message);
public event onReceiveMessage onMessageReceived;
public IModel Model { get; set; }
public IConnection Connection { get; set; }
public Subscription mSubscription { get; set; }
public string Hello(string name)
{
return "Hello";
}
public void StartConsuming()
{
isConsuming = true;
var connectionFactory = new ConnectionFactory();
connectionFactory.HostName = "localhost";
Connection = connectionFactory.CreateConnection();
//connect the model, exchange, queue and bind them together
bool durable = true;
//after connection create a channel so that you can communicate with the broker thru this channel.
IModel channel = Connection.CreateModel();
//after this declare an exchange and a queue and bind them together to this channel
if (!String.IsNullOrEmpty(EXCHANGE_NAME))
channel.ExchangeDeclare(EXCHANGE_NAME, ExchangeType.Direct, durable);
if (!String.IsNullOrEmpty(QUEUE_NAME))
{
channel.QueueDeclare(QUEUE_NAME, false, false, false, null);
channel.QueueBind(QUEUE_NAME, EXCHANGE_NAME, ROUTING_KEY, null);
}
//once model,exchange, queue is created then start cosuming it.
bool autoAck = false;
//create a subscription
mSubscription = new Subscription(Model, QUEUE_NAME, autoAck);
while (isConsuming)
{
BasicDeliverEventArgs e = mSubscription.Next();
byte[] body = e.Body;
String tempStr = System.Text.Encoding.UTF8.GetString(body);
tempStr = "Processed message = " + tempStr;
body = System.Text.Encoding.UTF8.GetBytes(tempStr);
if (onMessageReceived != null)
{
//this is not working. I have to write an event handler or some sort of delegate to pass the message back to the calling program
//and still waiting here for further messages from the server.
onMessageReceived(body);
}
mSubscription.Ack(e);
}
}
}