123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341 |
- using log4net;
- using Microsoft.Extensions.Hosting;
- using RabbitMQ.Client;
- using System;
- using System.Text;
- using System.Threading;
- using System.Threading.Tasks;
- using Ropin.Environmentally.AlarmService.Model;
- using RabbitMQ.Client.Events;
- using System.Net.Http;
- using System.Net;
- using Ropin.Inspection.Model;
- using Newtonsoft.Json;
- using Ropin.Inspection.Service;
- using Newtonsoft.Json.Linq;
- using System.Collections.Generic;
- using System.Text.RegularExpressions;
- using InfluxData.Net.Common.Enums;
- using InfluxData.Net.InfluxDb;
- using System.Linq;
- using InfluxData.Net.InfluxDb.Models;
- namespace Ropin.Environmentally.AlarmService.Service
- {
- public class RabbitMQReceiveService : IHostedService, IDisposable
- {
- private readonly IServiceProvider _provider;
- private static readonly ILog log = LogManager.GetLogger(typeof(RabbitMQReceiveService));
- private readonly IHttpClientFactory httpClientFactory;
- private readonly CofingSetModel _cofingSetModel;
- private readonly RabbitMQModel _rabbitMQModel;
- private readonly IPushMsgService _pushMsgService;
- private InfluxDbClient clientDb;
- public RabbitMQReceiveService(IServiceProvider provider, CofingSetModel cofingSetModel, IHttpClientFactory httpClientFactory, IPushMsgService pushMsgService)
- {
- this._provider = provider;
- _cofingSetModel = cofingSetModel;
- if (cofingSetModel != null)
- {
- _rabbitMQModel = cofingSetModel.RabbitMQ;
- }
- IniInflux();
- this.httpClientFactory = httpClientFactory;
- _pushMsgService = pushMsgService;
- }
- private IConnection con;
- private IModel channel;
- public Task StartAsync(CancellationToken cancellationToken)
- {
- Task.Run(async () =>
- {
-
-
-
-
-
-
- await AddRabbitMQ();
-
-
-
-
-
-
- });
- return Task.CompletedTask;
- }
- public async Task AddRabbitMQ()
- {
- try
- {
- var factory = new ConnectionFactory()
- {
- HostName = _rabbitMQModel.HostName,
- Port = _rabbitMQModel.Port,
- UserName = _rabbitMQModel.UserName,
- VirtualHost = _rabbitMQModel.VirtualHost,
- Password = _rabbitMQModel.Password,
- };
- if (con == null || con.IsOpen == false)
- {
- con = factory.CreateConnection();
- }
- if (channel == null || channel.IsOpen == false)
- {
- channel = con.CreateModel();
- }
- channel.ExchangeDeclare(_rabbitMQModel.ExchangeName, type: ExchangeType.Direct);
-
- var queueName = channel.QueueDeclare(
- queue: _rabbitMQModel.QueueName,
- durable: true,
- exclusive: false,
- autoDelete: false,
- arguments: null
- ).QueueName;
- channel.QueueBind(queueName, _rabbitMQModel.ExchangeName, _rabbitMQModel.RoutingKey);
-
-
- ushort batchSize = 5000;
- channel.BasicQos(prefetchSize: 0, prefetchCount: batchSize, global: false);
-
- channel.ConfirmSelect();
-
- var consumer = new EventingBasicConsumer(channel);
- List<ulong> batchDeliveryTags = new List<ulong>();
- List<string> batchMessages = new List<string>();
- consumer.Received += async (model, ea) =>
- {
- try
- {
- bool result = false;
- var body = ea.Body.ToArray();
- var message = Encoding.UTF8.GetString(body);
- log.Info("【RabbitMQ】" + message);
- batchMessages.Add(new Random().Next(0, 101).ToString());
- batchDeliveryTags.Add(ea.DeliveryTag);
- if (batchMessages.Count >= batchSize)
- {
-
-
- result = await AddData(batchMessages, batchDeliveryTags);
- Console.WriteLine(batchMessages.Count);
- batchMessages.Clear();
-
-
- }
-
-
-
-
-
-
-
-
-
-
- }
- catch (Exception ex)
- {
- channel.BasicNack(ea.DeliveryTag, false, true);
- log.Info("【RabbitMQ-接收消息处理异常了】" + ex.Message);
- }
- };
-
- channel.BasicConsume(queue: _rabbitMQModel.QueueName, autoAck: false, consumer: consumer);
- }
- catch (Exception ex)
- {
- log.Info("【异常-RabbitMQ】" + ex.Message);
- }
- }
- private void IniInflux()
- {
-
- var infuxUrl = "http://124.71.132.255:8085/";
- var infuxUser = "admin";
- var infuxPwd = "123456";
-
- clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest);
- }
-
-
-
- public async Task<bool> AddData(List<string> devs, List<ulong> deliveryTags)
- {
- IList<Point> points = new List<Point>();
- var dbName = "fanyidb";
- foreach (string dev in devs)
- {
- try
- {
-
-
-
-
-
-
-
- string strId = "1111111111";
- string strDevSpotCode = "654654541321545";
- float dValue = Convert.ToSingle(dev);
- string strName = "ceshi";
-
- var point_model = new Point()
- {
- Name = "fanyidev",
- Tags = new Dictionary<string, object>()
- {
- { "Id", strDevSpotCode },
-
-
- { "name", strName }
-
-
- },
- Fields = new Dictionary<string, object>()
- {
- { "Val",dValue }
- },
- Timestamp = DateTime.UtcNow
- };
- points.Add(point_model);
-
-
- }
- catch (Exception ex)
- {
- continue;
- }
- }
- if (points.Any())
- {
- await clientDb.Client.WriteAsync(points, dbName);
-
- ulong lastDeliveryTag = deliveryTags[^1];
- channel.BasicAck(deliveryTag: lastDeliveryTag, multiple: true);
- }
-
- else
- return false;
- return true;
- }
-
-
-
-
-
- public async Task<bool> WebScadaAlarmExecute(string msgData)
- {
- bool result = false;
- try
- {
- var pushMsg = JsonConvert.DeserializeObject<TpushMsgModel>(msgData);
- Inspection.Common.Helper.RabbitMQModel rabbitMQModels =new Inspection.Common.Helper.RabbitMQModel();
- rabbitMQModels.QueueName = "rab.video.record.mqtt";
- rabbitMQModels.UserName = _rabbitMQModel.UserName;
- rabbitMQModels.Password = _rabbitMQModel.Password;
- rabbitMQModels.HostName = _rabbitMQModel.HostName;
- rabbitMQModels.Port = _rabbitMQModel.Port;
- rabbitMQModels.VirtualHost = _rabbitMQModel.VirtualHost;
- rabbitMQModels.ExchangeName = rabbitMQModels.QueueName+".DirectExchange";
- rabbitMQModels.RoutingKey = rabbitMQModels.QueueName + ".key";
- bool bols = await _pushMsgService.PushAlarmMsgAsync(pushMsg, pushMsg.Subject, rabbitMQModels);
- if (bols)
- {
- result = true;
- }
- }
- catch (Exception ex)
- {
- log.Info("【异常-WebScadaAlarmExecute】" + ex.Message);
- }
- return result;
- }
-
-
-
-
-
- public async Task<bool> WebScadaAlarmExecuteAPI(string msgData)
- {
- bool result = false;
- try
- {
- using (HttpClient httpClient = httpClientFactory.CreateClient())
- {
- var httpRequestMessage = new HttpRequestMessage
- {
- Method = HttpMethod.Post,
- RequestUri = new Uri(_cofingSetModel.PublicPushMessageAPI),
- Content = new StringContent(msgData, Encoding.UTF8, "application/json")
- };
- var response = await httpClient.SendAsync(httpRequestMessage);
- string responseResult = await response.Content.ReadAsStringAsync();
- if (response.StatusCode != HttpStatusCode.OK)
- {
- log.Info($"【错误-WebScadaAlarmExecute】WebScada服务的设备报警 发送数据失败【{msgData}】");
- }
- else
- {
-
- receiveModel resultReturn = JsonConvert.DeserializeObject<receiveModel>(responseResult);
- if (resultReturn.code == "0") { result = true; }
- }
- }
- }
- catch (Exception ex)
- {
- log.Info("【异常-WebScadaAlarmExecute】" + ex.Message);
- }
- return result;
- }
- public Task StopAsync(CancellationToken cancellationToken)
- {
- Dispose();
- return Task.CompletedTask;
- }
- public void Dispose()
- {
- if (channel!=null)
- {
- channel.Close();
- }
- if (con!=null)
- {
- con.Close();
- }
- }
- }
- public class receiveModel
- {
- public string code { get; set; }
- public string message { get; set; }
- }
- }
|