RabbitMQ-基于RPC实现
对于使用RabbitMQ执行Command的情况,有时候需要有返回值信息。此时相当于client发布一个command后,并侦听返回结果的queue,server接收并处理,将处理结果发布到client侦听的queue中。简单实现如下:
1. Client端
private static void RPCResponse() { using (IConnection conn = CreateMQConnection()) { using (IModel ch = conn.CreateModel()) { while (true) { BasicGetResult res = ch.BasicGet("q1", false/*noAck*/); if (res != null) { try { string message = UTF8Encoding.UTF8.GetString(res.Body); ch.BasicAck(res.DeliveryTag, false); //返回数据 ch.ExchangeDeclare("e2", ExchangeType.Direct); ch.QueueDeclare("q2", true, false, false, null); ch.QueueBind("q2", "e2", "r2"); ch.BasicPublish("e2", "r2", null, Encoding.UTF8.GetBytes(message));//发布返回结果到q2中 } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } } } }
2. Server端
public static void SendCommand_Direct() { while (true) { JObject joMessage = new JObject(); joMessage.Add("to", "all"); joMessage.Add("from", "zsw"); joMessage.Add("message", "hello everyone!"); joMessage.Add("type", "Direct"); joMessage.Add("time", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); JObject jo = new JObject(); jo.Add("command", "chat"); jo.Add("data", JsonHelper.GetClearString(joMessage)); string message = JsonHelper.GetClearString(jo); string _requestExchange = "e1"; string route = "r1"; string queue = "q1"; try { using (IConnection connection = CreateMQConnection()) { using (IModel channel = connection.CreateModel()) { channel.ExchangeDeclare(_requestExchange, ExchangeType.Direct); channel.QueueDeclare(queue, true, false, false, null); channel.QueueBind(queue, _requestExchange, route); channel.BasicPublish(_requestExchange, route, null, Encoding.UTF8.GetBytes(message)); Console.WriteLine(string.Format("Direct publish message:{0}", message)); BasicGetResult res = channel.BasicGet("q2", false/*noAck*/);//从q2中获取返回结果 if (res != null) { try { string rpcMessage = UTF8Encoding.UTF8.GetString(res.Body); Console.WriteLine("rpc:" + rpcMessage); channel.BasicAck(res.DeliveryTag, false); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } } } } } catch (Exception ex) { throw ex; } Thread.Sleep(3000); } }