Blame view

HHECS.DAQServer/Services/RabbitMQHandleBackgroundService.cs 6.61 KB
唐召明 authored
1
using HHECS.BllModel;
唐召明 authored
2
using HHECS.DAQShared.Dto;
唐召明 authored
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using HHECS.DAQShared.Models;
using RabbitMQ.Client;
using System.Text.Json;

namespace HHECS.DAQServer.Services
{
    /// <summary>
    /// RabbitMQ存储线程
    /// </summary>
    public class RabbitMQHandleBackgroundService : BackgroundService
    {
        private readonly IFreeSql _freeSql;
        private readonly DataCacheService _dataCacheService;
        private readonly ILogger<RabbitMQHandleBackgroundService> _logger;
        private DateTime _lastReloadTime = DateTime.MinValue;

        private List<EquipmentExtend> _equipments = new List<EquipmentExtend>();

        private List<EquipmentTypeExtend> _equipmentTypes = new List<EquipmentTypeExtend>();
唐召明 authored
23
24
25
        /// <summary>
        /// 是否为生产环境
        /// </summary>
唐召明 authored
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
        private readonly bool _isProductionEnvironment;

        /// <summary>
        /// 数据刷新时间 间隔
        /// </summary>
        private readonly TimeSpan _reloadTimeSpan = TimeSpan.FromMinutes(1);

        public RabbitMQHandleBackgroundService(IFreeSql freeSql, DataCacheService dataCacheService, IConfiguration configuration, ILogger<RabbitMQHandleBackgroundService> logger)
        {
            _freeSql = freeSql;
            _dataCacheService = dataCacheService;
            _logger = logger;
            _isProductionEnvironment = configuration.GetValue<bool>("IsProductionEnvironment");
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
唐召明 authored
43
44
            //缓存推送失败的数据
            EquipmentDataDto failTemp = null;
唐召明 authored
45
46
47
48
49
            var factory = new ConnectionFactory()
            {
                HostName = "172.16.29.90",
                UserName = "producer",
                Password = "Aa123456",
唐召明 authored
50
                VirtualHost = _isProductionEnvironment ? "hhecs.daq" : "hhecs.daq.development"
唐召明 authored
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
            };
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    if (_dataCacheService.EquipmentDataRecordQueue.IsEmpty)
                    {
                        await Task.Delay(1000, stoppingToken);
                        continue;
                    }

                    //每分钟刷新一次
                    if ((DateTime.Now - _lastReloadTime) > _reloadTimeSpan)
                    {
                        var result = ReloadData();
                        if (!result.Success)
                        {
                            _logger.LogError($"[{nameof(RabbitMQHandleBackgroundService)}]线程,数据刷新失败:{result.Msg}");
                        }
                        _lastReloadTime = DateTime.Now;
                    }

                    if (_equipments.Count == 0 || _equipmentTypes.Count == 0)
                    {
                        await Task.Delay(1000, stoppingToken);
                        continue;
                    }

                    using var connection = factory.CreateConnection();
                    var total = 0;
                    do
                    {
                        //队列为空,结束循环
                        if (_dataCacheService.EquipmentDataRecordQueue.IsEmpty)
                        {
                            break;
                        }
唐召明 authored
89
90
91
92
93
94
95
96
97
98
99
100
                        EquipmentDataDto currentData = null;
                        if (failTemp == null)
                        {
                            _dataCacheService.EquipmentDataRecordQueue.TryDequeue(out currentData);
                        }
                        else
                        {
                            //上一次推送失败,则继续使用上一次的数据
                            currentData = failTemp;
                        }

                        if (currentData == null)
唐召明 authored
101
                        {
唐召明 authored
102
                            continue;
唐召明 authored
103
                        }
唐召明 authored
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

                        var equipmentTypeId = _equipments.Where(x => x.Code == currentData.EquipmentSN).Select(x => x.EquipmentTypeId).FirstOrDefault();
                        if (equipmentTypeId == default)
                        {
                            failTemp = null;
                            continue;
                        }

                        var equipmentTypeCode = _equipmentTypes.Where(x => x.Id == equipmentTypeId).Select(x => x.Code).FirstOrDefault();

                        if (string.IsNullOrWhiteSpace(equipmentTypeCode))
                        {
                            failTemp = null;
                            continue;
                        }

                        using var channel = connection.CreateModel();
                        var exchangeName = equipmentTypeCode;
                        channel.ExchangeDeclare(exchangeName, ExchangeType.Topic, true);

                        // 数据
                        var body = JsonSerializer.SerializeToUtf8Bytes(currentData);
                        var properties = channel.CreateBasicProperties();
                        properties.Persistent = true;
                        properties.DeliveryMode = 2;
                        channel.BasicPublish(exchangeName, $"{equipmentTypeCode}.{currentData.EquipmentSN}", properties, body);
                        failTemp = null;//推送成功后清空
                        total++;

                    } while (DateTime.Now - _lastReloadTime <= _reloadTimeSpan);
唐召明 authored
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

                    if (total > 0)
                    {
                        _logger.LogInformation($"成功写入{total}条数据");
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"[{nameof(RabbitMQHandleBackgroundService)}]线程异常:{ex.Message}");
                }
            }
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        private BllResult ReloadData()
        {
            try
            {
                _equipments = _freeSql.Queryable<EquipmentExtend>().ToList(x => new EquipmentExtend
                {
                    Id = x.Id,
                    Code = x.Code,
                    Name = x.Name,
                    EquipmentTypeId = x.EquipmentTypeId,
                });
                _equipmentTypes = _freeSql.Queryable<EquipmentTypeExtend>().ToList(x => new EquipmentTypeExtend
                {
                    Id = x.Id,
                    Code = x.Code,
                    Name = x.Name,
                });
                return BllResultFactory.Success();
            }
            catch (Exception ex)
            {
                return BllResultFactory.Error(ex.Message);
            }
        }
    }
}