BaseInfoCacheService.cs 5.02 KB
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.POJO.Entity;
using Hh.Mes.Service.Repository;
using Microsoft.Extensions.Caching.Distributed;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace Hh.Mes.Service
{
    /// <summary>
    /// 公共信息缓存   只负责读取数据 缓存 
    /// </summary>
    public class BaseInfoCacheService : RepositorySqlSugar<sys_user>
    {
        private readonly IDistributedCache _cache;

        private Dictionary<string, string> baseSql { get; set; }

        public BaseInfoCacheService(IDistributedCache cache)
        {
            baseSql = ConfigRead.GetInstance.GetBaseInfoSql();
            _cache = cache;
        }

        /// <summary>
        /// 第一次默认把所有的基础信息缓存
        /// </summary>
        public void SetBaseInfoCacheFirst()
        {
            try
            {
                var sql = GetAllFileJosnSql();
                var ds = Context.Ado.GetDataSetAllAsync(sql).Result;
                var index = 0;
                foreach (var item in baseSql)
                {
                    var jsonStr = JsonConvert.SerializeObject(ds.Tables[index], new DataTableConverter());
                    var cacheOption = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(1));
                    _cache.Set(item.Key, Encoding.UTF8.GetBytes(jsonStr), cacheOption);
                    index++;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine();
                Console.WriteLine($"WebApp Connection DataBase Error!Please Check Connection 【{ConfigRead.GetInstance.GetAppsetConnection().BaseDBContext}】");
                Console.WriteLine();
                Log4NetHelper.Instance.Error(ex.Message);
            }
        }

        /// <summary>
        /// 获取缓存数据
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="isRemove"> true 重新设置值</param>
        /// <returns></returns>
        public string GetOneBaseInfo(string key, bool isRemove = false)
        {
            if (!baseSql.ContainsKey(key))
            {
                return string.Empty;
            }
            var sql = baseSql[key];
            if (isRemove)
            {
                return getDataBySql(sql, key);
            }
            var bytes = _cache.Get(key);
            if (bytes != null)
            {
                return Encoding.UTF8.GetString(bytes);
                //var dt = JsonSerializer.Deserialize<DataTable>(Encoding.UTF8.GetString(bytes));
                //return JsonConvert.SerializeObject(dt, new DataTableConverter());
            }
            return getDataBySql(sql, key);
        }

        /// <summary>
        /// 读取数据库数据,并存入缓存
        /// </summary>
        private string getDataBySql(string sql, string key)
        {
            var dt = Context.Ado.GetDataTableAsync(sql).Result;
            var jsonStr = JsonConvert.SerializeObject(dt, new DataTableConverter());
            var cacheOption = new DistributedCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMinutes(1));
            _cache.Set(key, Encoding.UTF8.GetBytes(jsonStr), cacheOption);
            return JsonConvert.SerializeObject(dt, new DataTableConverter());
        }

        /// <summary>
        /// 获取所有的配置文件json sql
        /// </summary>
        /// <returns></returns>
        private string GetAllFileJosnSql()
        {
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var item in baseSql)
            {
                stringBuilder.AppendLine(item.Value);
            }
            return stringBuilder.ToString();
        }

        /// <summary>
        /// api 启动检查数据库是否已连接上
        /// </summary>
        public void CheckDatabaseConnected()
        {
            var isConnection = false;
            ExceptionsHelp.Instance.ExecuteT(() =>
            {
                Console.WriteLine();
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine($"The database is being connected......");
                Console.WriteLine();
                var sql = baseSql["base_factory"];
                Context.Ado.GetDataTable(sql);
                return "";
            }, actionCatCh: () =>
            {
                isConnection = true;
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine();
                Console.WriteLine($"The database connection is  Error!Please Check Connection 【{ConfigRead.GetInstance.GetAppsetConnection().BaseDBContext}】");
                Console.WriteLine();
                Console.ResetColor();
            }, actionFinally: () =>
            {
                if (!isConnection) Console.WriteLine("The database connection is successful");
            });
        }
    }
}