67 lines
2.0 KiB
C#
67 lines
2.0 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
|
|
namespace YLErp.Modules.RiskEngine
|
|
{
|
|
/// <summary>
|
|
/// 规则编译结果的进程内缓存。
|
|
/// 当前第一版按 RuleCode 缓存 Roslyn 编译后的可执行委托。
|
|
/// </summary>
|
|
public static class RuleCompiledCache
|
|
{
|
|
/// <summary>
|
|
/// 规则编译结果的进程内缓存。ConcurrentDictionary为线程安全的字典,用于缓存编译后的规则委托,性能略低。
|
|
/// </summary>
|
|
private static readonly ConcurrentDictionary<string, Func<RiskContext, bool>> Cache
|
|
= new ConcurrentDictionary<string, Func<RiskContext, bool>>(StringComparer.OrdinalIgnoreCase);
|
|
|
|
/// <summary>
|
|
/// 写入或更新规则编译结果。
|
|
/// </summary>
|
|
public static void Set(string ruleCode, Func<RiskContext, bool> compiledScript)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ruleCode) || compiledScript == null)
|
|
{
|
|
return;
|
|
}
|
|
|
|
Cache[ruleCode] = compiledScript;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 尝试获取规则编译结果。
|
|
/// </summary>
|
|
public static bool TryGet(string ruleCode, out Func<RiskContext, bool> compiledScript)
|
|
{
|
|
compiledScript = null;
|
|
|
|
if (string.IsNullOrWhiteSpace(ruleCode))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
return Cache.TryGetValue(ruleCode, out compiledScript);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 删除指定规则的编译结果。
|
|
/// </summary>
|
|
public static void Remove(string ruleCode)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(ruleCode))
|
|
{
|
|
return;
|
|
}
|
|
|
|
Cache.TryRemove(ruleCode, out _);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 清空全部规则编译结果。
|
|
/// </summary>
|
|
public static void Clear()
|
|
{
|
|
Cache.Clear();
|
|
}
|
|
}
|
|
} |