获取源码

客户端代码:

namespace RabbitMQDemo
{
public partial class RPC : Form
{
private readonly static RPC _RPC;
Action<string, TextBox> SetText;
static RPC()
{
_RPC = new RPC();
}
/// <summary>
/// 单例模式
/// </summary>
public static RPC SingleForm { get { return _RPC; } }
private RPC()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
} private void btnSendMsg_Click(object sender, EventArgs e)
{//RPC客户端发出请求
string message = txtPublisher.Text;
if (message.Trim().Length <= )
{
MessageBox.Show("请输入要发送的消息");
}
RpcClient client = new RpcClient();
var response = client.Call(message);
txtRpcClient.Text += string.Format("{0}\r\n", response);
client.Close();
} /// <summary>
/// 客户端类
/// </summary>
private class RpcClient
{
#region 参数
/// <summary>
/// rabbitmq连接
/// </summary>
private readonly IConnection connection;
/// <summary>
/// 通道
/// </summary>
private readonly IModel channel;
/// <summary>
/// 客户端关联的队列
/// </summary>
private readonly string replyQueueName;
/// <summary>
/// 消费者
/// </summary>
private readonly EventingBasicConsumer consumer;
//private readonly BlockingCollection<string> resQueue = new BlockingCollection<string>(); private readonly BlockingCollection<string> resQueue = new BlockingCollection<string>();
/// <summary>
/// 消息属性
/// </summary>
private readonly IBasicProperties props;
#endregion
/// <summary>
/// 构造函数
/// </summary>
public RpcClient()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
connection = factory.CreateConnection();
channel = connection.CreateModel();
replyQueueName = channel.QueueDeclare().QueueName;
consumer = new EventingBasicConsumer(channel);
props = channel.CreateBasicProperties();
//关联response,request和replyQueueName
var correlationID = Guid.NewGuid().ToString();
props.CorrelationId = correlationID;
props.ReplyTo = replyQueueName; consumer.Received += (model, ea) =>
{
var response = Encoding.UTF8.GetString(ea.Body);
//确定返回的响应是这个请求发出的
if (ea.BasicProperties.CorrelationId == correlationID)
resQueue.Add(response);
};
} public string Call(string msg)
{
var msgBytes = Encoding.UTF8.GetBytes(msg);
channel.BasicPublish(exchange: "",
routingKey: "rpc_queue",
basicProperties: props,
body: msgBytes); channel.BasicConsume(
consumer: consumer,
queue: replyQueueName,
noAck: true); return resQueue.Take();
} public void Close()
{
connection.Close();
}
}//class
}
}

服务端代码:

namespace RpcServer
{
public partial class RpcServer : Form
{
private readonly static RpcServer _RpcServer;
Action<string, TextBox> SetText;
static RpcServer()
{
_RpcServer = new RpcServer();
}
/// <summary>
/// 单例模式
/// </summary>
public static RpcServer SingleForm { get { return _RpcServer; } }
private RpcServer()
{
CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
ReceiveMsg(txtRpcServer);//服务端
SetText += OnSetText;
} /// <summary>
/// 服务端接收消息
/// </summary>
private void ReceiveMsg(TextBox box)
{
try
{
var factory = new ConnectionFactory() { HostName = "localhost" };
var connection = factory.CreateConnection();
var channel = connection.CreateModel(); //声明队列
channel.QueueDeclare(queue: "rpc_queue",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null); //每个消费者最多消费一条消息,没返回消息确认之前不再接收消息
channel.BasicQos(, , false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) =>
{
string response = null;
var body = ea.Body;
var props = ea.BasicProperties;
var replyProps = channel.CreateBasicProperties();
replyProps.CorrelationId = props.CorrelationId;
var msg = Encoding.UTF8.GetString(body);
//服务端显示内容
box.Invoke(SetText, msg, box);
response = "我将给你回复:已收到消息-" + msg; var responseBytes = Encoding.UTF8.GetBytes(response);
channel.BasicPublish(exchange: "",
routingKey: props.ReplyTo,
basicProperties: replyProps,
body: responseBytes);
//手动向rabbitmq发送消息确认
channel.BasicAck(deliveryTag: ea.DeliveryTag,
multiple: false);
};
channel.BasicConsume(queue: "rpc_queue",
noAck: false,//手动确认消息
consumer: consumer);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
} private void OnSetText(string text, TextBox box)
{
box.Text += string.Format("{0}\r\n", text);
}
}
}

界面:

大概流程:

客户端模拟发送一个请求到队列,服务端从队列消费消息并模拟发送一个响应到队列,客户端消费该消息(新建2个winform程序测试,一个客户端,一个服务端)

vs同时启动两个winform程序:鼠标点击解决方案-右键属性-多个启动项目-操作改为启动-确定-即可

测试结果:

WinForm实现Rabbitmq官网6个案例-RPC的更多相关文章

  1. WinForm实现Rabbitmq官网6个案例-Publishe/Subscribe

    代码: namespace RabbitMQDemo { public partial class PublishSubscribe : Form { private string exchangeN ...

  2. WinForm实现Rabbitmq官网6个案例-Work Queues

    代码: namespace RabbitMQDemo { public partial class WorkQueues : Form { private string queueName = &qu ...

  3. WinForm实现Rabbitmq官网6个案例-Hello World

    先上代码 namespace RabbitMQDemo { public partial class HelloWorld : Form { string queueName1 = "hel ...

  4. WinForm实现Rabbitmq官网6个案例-Topics

    代码: namespace RabbitMQDemo { public partial class Topics : Form { private string exchangeName = &quo ...

  5. WinForm实现Rabbitmq官网6个案例-Routing

    代码: namespace RabbitMQDemo { public partial class Routing : Form { private string exchangeName = &qu ...

  6. 官网英文版学习——RabbitMQ学习笔记(一)认识RabbitMQ

    鉴于目前中文的RabbitMQ教程很缺,本博主虽然买了一本rabbitMQ的书,遗憾的是该书的代码用的不是java语言,看起来也有些不爽,且网友们不同人学习所写不同,本博主看的有些地方不太理想,为此本 ...

  7. 2022年官网下安装RabbitMQ最全版与官网查阅方法

    目录 一.Erlang环境部署 1.百度搜索"Erlang",或者访问网址:https://www.erlang.org/,找到DOWNLOAD双击进入. 2.找到支持的windo ...

  8. Yeoman 官网教学案例:使用 Yeoman 构建 WebApp

    STEP 1:设置开发环境 与yeoman的所有交互都是通过命令行.Mac系统使用terminal.app,Linux系统使用shell,windows系统可以使用cmder/PowerShell/c ...

  9. MXNet官网案例分析--Train MLP on MNIST

    本文是MXNet的官网案例: Train MLP on MNIST. MXNet所有的模块如下图所示: 第一步: 准备数据 从下面程序可以看出,MXNet里面的数据是一个4维NDArray. impo ...

随机推荐

  1. linux 将进程或者线程绑定到指定的cpu上

    基本概念 cpu亲和性(affinity) CPU的亲和性, 就是进程要在指定的 CPU 上尽量长时间地运行而不被迁移到其他处理器,也称为CPU关联性:再简单的点的描述就将指定的进程或线程绑定到相应的 ...

  2. Pycharm 报错 AttributeError: module 'pip' has no attribute 'main'

    1.打开文件packaging_tool.py: D:\Program files\pycharm\PyCharm 2016.3.2\helpers\packaging_tool.py 2.添加导入: ...

  3. (转)DB2性能优化 – 如何通过调整锁参数优化锁升级

    原文:http://blog.51cto.com/5063935/2074306 1.概念描述 所谓的锁升级(lock escalation),是数据库的一种作用机制,为了节约内存的开销, 其会将为数 ...

  4. javascript绑定事件addEventListener与attachEvent

    1.eleObj.addEventListener(eventName,handle,useCapture); eleObj:DOM元素: eventName:事件名称.注意,这里的事件名称没有“ o ...

  5. 【文档】六、Mysql Binlog版本

    binlog文件格式有以下几种: v1:用于3.23版本 v3:用于4.0.2到4.1版本 v4:用于5.0及以上版本 v2版本只在4.0.x版本中使用,目前已经不再支持了. 处理binlog的程序必 ...

  6. jQuery Mobile 实现苹果滑动删除闹钟功能的几点总结

    1.jquery给动态添加的元素添加事件 在jquery推出新版本,使用.on()以前,我们会用.live()来为动态添加的代码绑定事件,但是现在jQuery用.on()替代了.live() 先看个. ...

  7. js实现私有变量

    一.块级作用域 js中没有块级作用域的概念,可用匿名函数实现,由于匿名函数执行完一遍后,内部没有引用其变量对象的函数,其变量对象被清除,后面则引用不到其中的变量 (function(){ //块级作用 ...

  8. GitBook入门(用github做出第一本书)——超详细配图说明

    我最近接触到gitbook,发现它支持markdown和git,刚好把我之前在github上的笔记可以生成一本书,于是我就开始着手捣鼓gitbook,一下午的时间就弄的差不多了,说明这个东西还是挺容易 ...

  9. 解决问题的思维方式之Problem->Desgin->Solution(笔记)

    Problem->Desgin->Solution: 1.对于每个需要实现的功能问题,我们都称之为Problem(问题). 2.解决问题的具体思考过程,寻求解决问题的方案,即为Desgin ...

  10. C#(winform)为button添加背景图片,并去掉各种边框

    1.既然是添加背景图片 所以这里应该使用 Button.BackgroudImage = "" ;来设置图片 而不应该使用  Button.Image = "" ...