static IModel model;
public IModel RetrieveSomeSharedIModelInstance()
{
if (model == null)
{
var factory = new ConnectionFactory()
{
HostName = "10.10.0.210",
UserName = "1",
Password = "1",
//Port = options.Value.RabbitPort,
};
IConnection _connection = factory.CreateConnection();
model = _connection.CreateModel();
model.QueueDeclare(queue: "Test",
durable: true,
exclusive: false,
autoDelete: false,
arguments: null);
}
return model;
}
public void SendMessage(string message)
{
try
{
IModel _channel = RetrieveSomeSharedIModelInstance();
var properties = _channel.CreateBasicProperties();
properties.DeliveryMode = 2;//資料模式:1不持久化,2持久化
string msgJson = DataManage.ObjToJson.ObjectToJsonOfNewton(message);
var body = System.Text.Encoding.UTF8.GetBytes(msgJson);
lock (_channel)
{
_channel.BasicPublish(exchange: "",
routingKey: "Test",
basicProperties: properties,
body: body);
}
}
catch (Exception e)
{
throw (e);
}
}
按照官方檔案說法,應該避免多個執行緒同時使用IModel實體,在使用時加鎖,那么這個鎖只能加到BasicPublish上。上面的代碼如果將QueueDeclare也放到鎖內的話,即多執行緒同時宣告佇列,就會報例外: "Pipelining of requests forbidden" 。
宣告佇列只能單執行緒操作嗎?加鎖也不好使?
如果不放到 發送訊息之前的話,怎么確保佇列是存在的?
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/7997.html
標籤:網絡
