我有一個rabbitmq消費者應用程序實現「.net中的發佈/訂閱模式,它完美地作爲控制檯應用程序運行,但是當我將它部署爲Windows服務時,它似乎不會保存數據到MongoDB的。RabbitMQ消費者作爲Windows服務
protected override void OnStart(string[] args)
{
try
{
var connectionString = "mongodb://localhost";
var client = new MongoClient(connectionString);
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.ExchangeDeclare(exchange: "test", type: "fanout");
var queueName = channel.QueueDeclare().QueueName;
channel.QueueBind(queue: queueName, exchange: "logs", routingKey: "");
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
BsonDocument document = BsonDocument.Parse(message);
var database = client.GetDatabase("test");
var collection = database.GetCollection<BsonDocument>("test_collection");
collection.InsertOneAsync(document);
};
channel.BasicConsume(queue: queueName, noAck: true,consumer: consumer);
}
}
}
catch (Exception ex)
{
throw;
}
}
有什麼我失蹤?
你檢查了日誌嗎? – Gabriele
你不是在等待InsertOneAsync的結果......任何事情都可能發生,你永遠不會知道......使用collection.InsertOneAsync(document).GetAwaiter()。GetResult(); –
@Gabriele我確實嘗試了日誌記錄以查看消息是否真的被接收。但看起來不像。 – sandy