1. 程式人生 > >RabbitMQ訊息佇列、路由器、訊息的持久化

RabbitMQ訊息佇列、路由器、訊息的持久化

 

如有錯誤還請斧正,謝謝

```C#

//入列
ConnectionFactory factory = new ConnectionFactory { HostName = "localhost", UserName = "You`rName", Password = "You`rPassword" };//例項化連線工廠
using (IConnection conn = factory.CreateConnection())//建立連線
{
//建立通道
using (IModel im = conn.CreateModel())
{
//order為交換器名稱,ExchangeType為交換機型別(Direct,Fanout,Topic,Headers)具體使用場景在印象筆記中有記錄
im.ExchangeDeclare("order", ExchangeType.Direct,durable:true,autoDelete:false,arguments:null);
//creatorder為佇列名,第一個false是durable(持久化)第二個false是exclusive(是否排他)第三個false為autodelete(是否自動刪除)null為arguments(其他引數)
im.QueueDeclare("creatorder", durable:true,exclusive:false,autoDelete:false,arguments:null);
//creatorder為佇列名,order為交換器名,ExchangeType.Direct是路由key,null為arguments(其他引數)
im.QueueBind("creatorder", "order", ExchangeType.Direct, null);
byte[] message = ConvertToByteHelp.ObjectToBytes(order);//把物件轉換成bytes[]
IBasicProperties properties = im.CreateBasicProperties();
//properties.SetPersistent(true);佇列設定為持久化之後,需要將訊息也設定為持久化這是老方法已過時下面為先用新方法
properties.DeliveryMode = 2;//將訊息持久化的新方法
im.BasicPublish("order", ExchangeType.Direct, properties, message);//推送訊息
//im.BasicPublish("order", routingKey: "Direct", basicProperties: properties, body: message);
}
}

```