WinForm实现Rabbitmq官网6个案例-RPC

时间:2022-05-09 03:25:42

获取源码

客户端代码:

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);
}
}
}

界面:

WinForm实现Rabbitmq官网6个案例-RPC

WinForm实现Rabbitmq官网6个案例-RPC

大概流程:

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

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

WinForm实现Rabbitmq官网6个案例-RPC

测试结果:

WinForm实现Rabbitmq官网6个案例-RPC

WinForm实现Rabbitmq官网6个案例-RPC

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

  1. WinForm实现Rabbitmq官网6个案例-Publishe&sol;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. Yeoman 官网教学案例:使用 Yeoman 构建 WebApp

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

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

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

  9. spring原理案例-基本项目搭建 01 spring framework 下载 官网下载spring jar包

    下载spring http://spring.io/ 最重要是在特征下面的这段话,需要注意: All avaible features and modules are described in the ...

随机推荐

  1. 在线倍增法求LCA专题

    1.cojs 186. [USACO Oct08] 牧场旅行 ★★   输入文件:pwalk.in   输出文件:pwalk.out   简单对比时间限制:1 s   内存限制:128 MB n个被自 ...

  2. Versioned table in Netezza

    Problem One QC process need to obtain tables and their row counts in a database in Netezza. We use t ...

  3. SPOJ 4487 Splay 基本操作

    插入操作,删除操作和置换操作都是单点的,所以不需要lazy标记.这个很简单,都是两次RotateTo,一次Splay操作就搞定. 求最大连续字段和的操作和线段树的题目类似,只需要保存最左边的连续最大字 ...

  4. 利用VS2005进行dump文件调试

    前言:利用drwtsn32或NTSD进行程序崩溃处理,都可以生成可用于调试的dmp格式文件.使用VS2005打开生成的DMP文件,能很方便的找出BUG所在位置.本文将讨论以下内容: 1.  程序编译选 ...

  5. 从源码编译rpi的内核

    Kernel Building https://www.raspberrypi.org/documentation/linux/kernel/building.md There are two mai ...

  6. linux服务器开发二&lpar;系统编程&rpar;--线程相关

    线程概念 什么是线程 LWP:Light Weight Process,轻量级的进程,本质仍是进程(在Linux环境下). 进程:独立地址空间,拥有PCB. 线程:也有PCB,但没有独立的地址空间(共 ...

  7. 10亿美元融资腾讯跟头,Grail要用基因测序做癌症早期筛查

    癌症超早期筛查:"在干草堆中寻找缝衣针"癌症是人类的噩梦,尤其是中晚期癌症,但很多时候,当患者感觉到身体不适而去医院检查时,病情都已经到了中晚期,很难治愈.而有研究表明,早期癌症患 ...

  8. nginx系列12:一致性哈希算法

    前面一节的hash算法存在一个问题,当上游的应用服务器因某一台down掉导致服务器数量发生变化时,会导致大量的请求路由策略失效,一致性哈希算法可以缓解这个问题. 一致性哈希算法 1,hash算法存在的 ...

  9. BIML 101 - ETL数据清洗 系列 - BIML 快速入门教程 - 连接数据库执行SQL语句

    BIML 101 - BIML 快速入门教程 第一节 连接数据库执行SQL语句 本小节将用BIML建一个简单的可以执行的包. 新建一个biml文件,贴入下面的代码 1 <Biml xmlns=& ...

  10. office2007每次打开都要配置文件,怎么取消配置

    有时候 Office2007打开文档,每次都提示需要安装.配置,配置完成之后,下次打开又需要配置点击取消就不能打开.非常的烦.ffice2007下载后为什么每次打开总需要置?office2007每次打 ...