using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace DS.WMS.FeeBillRecvService { public class RecvFeeBillWorker : BackgroundService { private readonly ILogger _logger; private IConnection mqConn; private IModel model; public RecvFeeBillWorker(ILogger logger) { _logger = logger; } public override async Task StartAsync(CancellationToken stoppingToken) { try { //while (!stoppingToken.IsCancellationRequested) //{ // _OpServer = new BackgroundJobServer(new BackgroundJobServerOptions // { // SchedulePollingInterval = TimeSpan.FromMinutes(1), // ServerName = "OpWorkService", // Queues = new[] { "op" } // }); // await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken); //} } catch (OperationCanceledException ex) { Console.WriteLine(ex.ToString()); } catch (Exception ex) { Console.WriteLine(ex.ToString()); //Environment.Exit(1); } } protected override Task ExecuteAsync(CancellationToken stoppingToken) { _logger.LogInformation("启动j账单 ExecuteAsync"); return Task.Run(() => { _logger.LogInformation("BookingAutoService ExecuteAsync RunTask"); //绑定队列 BindMQ(); }); } private void BindMQ() { string ExchangeName = "billcenter.output.ds7new.444c19c1-0bf5-4709-a08b-c9859ca775e6"; string QueueName = $"billcenter.output.ds7new.444c19c1-0bf5-4709-a08b-c9859ca775e6"; ConnectionFactory factory = new ConnectionFactory(); //var repoSysCfg = _serviceScope.ServiceProvider.GetService>(); var mqUrl = "amqp://djy_mail:djymailqwe@47.104.207.5:12567/djy_email_parser"; //var mqUrl = repoSysCfg.FirstOrDefault(x => x.Code == "DjyBookingAutoMQUrl")?.Value; if (string.IsNullOrEmpty(mqUrl)) { _logger.LogError($"接收订舱自动化消息推送所需MQUrl未配置"); } else { _logger.LogInformation($"准备连接订舱自动化消息队列:{mqUrl}"); factory.Uri = new Uri(mqUrl); mqConn = factory.CreateConnection("东胜8接收账单邮件解析"); model = mqConn.CreateModel(); model.ExchangeDeclare(ExchangeName, ExchangeType.Topic); model.QueueDeclare(QueueName, false, false, true, null); model.QueueBind(QueueName, ExchangeName, "*", null); var consumer = new EventingBasicConsumer(model); consumer.Received += (obj, arg) => { var body = arg.Body; var strBody = Encoding.UTF8.GetString(body.ToArray()); _logger.LogInformation($"收到订舱自动化消息队列:{strBody}"); }; model.BasicConsume(QueueName, true, consumer); } } public override void Dispose() { base.Dispose(); //_serviceScope.Dispose(); if (mqConn != null && mqConn.IsOpen) mqConn.Close(); _logger.LogInformation("BookingAutoService Dispose"); } private async Task DoWork(CancellationToken cancellationToken) { // 这里放你的业务逻辑代码 await Task.CompletedTask; } } }