BaseInfoCacheService.cs
3.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Common.Redis;
using Hh.Mes.POJO.Entity;
using Hh.Mes.Service.Repository;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace Hh.Mes.Service
{
/// <summary>
/// 公共信息缓存 只负责读取数据 缓存
/// </summary>
public class BaseInfoCacheService : RepositorySqlSugar<sys_user>
{
private Dictionary<string, string> baseSql { get; set; }
private RedisBase cli { get; set; }
public BaseInfoCacheService()
{
baseSql = ConfigRead.GetInstance.GetBaseInfoSql();
cli=new RedisBase();
}
/// <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 json = JsonConvert.SerializeObject(ds.Tables[index], new DataTableConverter());
cli.Set(item.Key, json);
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 "";
var sql = baseSql[key];
if (isRemove) return getDataBySql(sql, key);
return cli.ExistsKey(key) ? cli.redisClient.Get(key) : getDataBySql(sql, key);
}
/// <summary>
/// 读取数据库数据,并存入缓存
/// </summary>
private string getDataBySql(string sql, string key)
{
Random rd = new Random();
var expirestime = rd.Next(cli.dayTime, cli.dayTimeTwo);
var dt = Context.Ado.GetDataTableAsync(sql).Result;
var jsonStr = JsonConvert.SerializeObject(dt, new DataTableConverter());
cli.Set(key, jsonStr, expirestime);
return jsonStr;
}
/// <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();
}
public DataTable GetMaterialList()
{
//var sqlMater = baseSql["base_material"];
//var dt = Context.Ado.GetDataTable(sqlMater);
return null;
}
}
}