Files
juipnet/Infrastructure/Hncore.Infrastructure/Common/ConcurrentHelper.cs
“wanyongkang” ed3b2c653e 接口文件
2024-04-10 13:55:27 +08:00

75 lines
1.9 KiB
C#

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;
using MySql.Data.MySqlClient;
namespace Hncore.Infrastructure.Common
{
public class ConcurrentHelper
{
private static string _connString = "";
private static string _tableName = "concurrent_helper";
private List<string> _infos = new List<string>();
private string _id;
public static void Init(string mysqlConn)
{
_connString = mysqlConn;
MySqlHelper.Execute(_connString
, $@"create table if not exists {_tableName}
(
Id VARCHAR(32) PRIMARY KEY UNIQUE,
CreateTime datetime DEFAULT now(),
Info text
)"
);
}
public ConcurrentHelper AddInfo(string info)
{
_infos.Add(info);
return this;
}
private async Task<bool> GetAuthority()
{
try
{
string info = ListHelper<string>.ListToStr(_infos, "\n");
_id = SecurityHelper.GetMd5Hash(info);
string sql = $"insert into {_tableName}(Id,Info) values(@Id,@Info)";
await MySqlHelper.ExecuteAsync(_connString, sql, new {Id = _id, Info = info});
}
catch
{
return false;
}
return true;
}
public async Task Execute(Action action)
{
try
{
if (await GetAuthority())
{
action();
}
}
catch (Exception e)
{
await MySqlHelper.ExecuteAsync(_connString, $"DELETE FROM {_tableName} where Id='{_id}'");
throw e;
}
}
}
}