Created
March 11, 2013 03:57
-
-
Save zhuqling/5131809 to your computer and use it in GitHub Desktop.
RabbitMQ RPC服务器返回结果到客户端
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void Notify(IBasicConsumer sender, BasicDeliverEventArgs args) | |
{ | |
IBasicProperties msgProps = args.BasicProperties; | |
sender.Model.BasicAck(args.DeliveryTag, false); // 返回ACK应答信息 | |
// 得到公式,并进入计算 | |
string msgBody = Encoding.ASCII.GetString(args.Body); | |
var calcMessage = JsonConvert.DeserializeObject<CalcMessage>(msgBody); | |
// 显示公式 | |
txtResult.BeginInvoke(new UpdateMsgBodyDelegate(UpdateMsgBody), calcMessage.Formula); | |
string result = ""; | |
try | |
{ | |
// 按输入公式文本计算结果, 这里使用了FLEE库 | |
ExpressionContext context = new ExpressionContext(); | |
context.Imports.AddType(typeof (Math)); | |
// context.Variables["a"] = 100; | |
IDynamicExpression eDynamic = context.CompileDynamic(calcMessage.Formula); // "sqrt(a) + pi" | |
result = eDynamic.Evaluate().ToString(); | |
} | |
catch | |
{ | |
result = "表达式不正确,无法计算"; | |
} | |
// 返回计算结果(即另一个发送消息的过程) | |
string replyTo = (string)msgProps.ReplyTo; // ReplyTo为客户端生成的临时接收结果的Queue名称 | |
IBasicProperties returnMsgProps = new BasicProperties(); | |
returnMsgProps.DeliveryMode = 2; | |
// 重新发送消息到客户端的Queue,返回计算结果 | |
sender.Model.BasicPublish( | |
exchange: "", // 直接发送到Queue,不用路由 | |
routingKey: replyTo, | |
basicProperties: returnMsgProps, | |
body: Encoding.UTF8.GetBytes(result) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment