•  {ownerId}/snowflake.provider.json

{
  //雪花算法对应的10进制机器码   或  guid对应的机器码
  // string machineIdI = _configuration.GetValue<string>($"snowflake:{ownerId}:machine");
  //string datacenterId = _configuration.GetValue<string>($"snowflake:{ownerId}:{sysId}");
  "snowflake": {
    "bt": {
      "global": true,
      "machine": 1,
      "bt-20200601-main": "1",
      "bt-app": "2",
      "bt-backstage": "3",
      "bt-portal": "4",
      "default-dev": "5"
    }
  }
}
  •  IGuid 注入使用
private readonly IGuid _guidRepository;

        /// <summary>
        /// 注入服务
        /// </summary>
        /// <param name="cache"></param>
        public QuDataResultProvider(ICache cache, IGuid guidRepository, ILogger<QuDataResultProvider> logger, IDataResultCache dataResultCache)
        {
            //ISubPush isubPush,
            _cache = cache;
            _dataResultCache = dataResultCache;
            _logger = logger;
            _guidRepository = guidRepository;
            //_isubPush = isubPush;
        }
  •  Mapper里面开启雪花算法
  •  (savePrimary && sqlColumn.GuidMethod == GuidMethod.Snowflake)

    "policyId": {
      "guidMethod": "Snowflake"
    },


   /// <summary>
        /// 新增的默认参数
        /// </summary>
        /// <param name="pf"></param>
        /// <param name="sqlTable"></param>
        /// <param name="sqlConfig"></param>
        /// <param name="dictionaryUrl"></param>
        /// <param name="dicPK"></param>
        /// <param name="isChild"></param>
        public void SetDefaultParamsAdd(PFGlobalParameter pf, SqlTable sqlTable, SqlConfig sqlConfig, Dictionary<string, object> dictionaryUrl, Dictionary<string, object> dicPK, bool isChild)
        {
            //设置 guid 信息   20180907  cbg
            IEnumerable<SqlColumn> sqlColumnGuid = sqlConfig.ColumnsLst.Where<SqlColumn>(temp =>
            {
                return temp.TableId == sqlTable.Id && ValidateUtil.ValidateExistsValue(temp.GuidMethod) && (temp.GuidMethod != GuidMethod.GUID_DB || temp.GuidMethod != GuidMethod.NEW_ID) && temp.GuidMethod != GuidMethod.None;
            });
            foreach (SqlColumn sqlColumn in sqlColumnGuid)
            {
                if (!dicPK.ContainsKey(sqlColumn.Field)) continue;
                //表示外部传递进来的值
                //if (dicPK[sqlColumn.Field] != null && dicPK[sqlColumn.Field].ToString().Length > 2) continue;
                if (sqlConfig.ResponseFieldTemp.GuidMethod == GuidMethod.Out) continue;

                string guid = null;
                bool savePrimary = !isChild || dicPK[sqlColumn.Field] == null || string.IsNullOrEmpty(dicPK[sqlColumn.Field].ToString());

                if (_configuration.GetValue<bool>($"snowflake:{pf.OwnerId}:global"))
                {
                    guid = _guid.GetDataGuid(pf.OwnerId, pf.SysId, dictionaryUrl);
                    dicPK[sqlColumn.Field] = guid;
                }
                else if (savePrimary && sqlColumn.GuidMethod == GuidMethod.Snowflake)
                {
                    string machineIdI = _configuration.GetValue<string>($"snowflake:{pf.OwnerId}:machine") ?? "1";
                    string datacenterId = _configuration.GetValue<string>($"snowflake:{pf.OwnerId}:{pf.SysId}") ?? "-1";
                    GidSnowflakeUtil GidSnowflakeUtil = new GidSnowflakeUtil(Convert.ToInt32(machineIdI), Convert.ToInt32(datacenterId));
                    guid = GidSnowflakeUtil.GetId().ToString();
                    dicPK[sqlColumn.Field] = guid;
                }
                else if (savePrimary && dictionaryUrl.ContainsKey("_ownerId") && !string.IsNullOrEmpty(dictionaryUrl["_ownerId"]?.ToString()))
                {
                    guid = _guid.GetDataGuid(pf.OwnerId, pf.SysId, dictionaryUrl);
                    if (sqlColumn.GuidMethod == GuidMethod.GUID_08)
                    {
                        guid = guid.Split('-')[0];
                    }
                    string tempOwnerId = dictionaryUrl["_ownerId"].ToString();
                    if (tempOwnerId.Length > 8)
                    {
                        tempOwnerId = tempOwnerId.Substring(0, 8);
                    }
                    //标示ID来源项目,开头几位表示来源
                    string temp = guid.Substring(0, tempOwnerId.Length + 1);
                    dicPK[sqlColumn.Field] = guid.Replace(temp, $"{tempOwnerId}-").Replace("--", "-").Trim('-');
                }
                else if (savePrimary)
                {
                    guid = _guid.GetDataGuid(pf.OwnerId, pf.SysId, dictionaryUrl);
                    if (sqlColumn.GuidMethod == GuidMethod.GUID_08)
                    {
                        guid = guid.Split('-')[0];
                    }
                    dicPK[sqlColumn.Field] = guid;
                }
            }
            //设置使用系统内部默认的参数值
            bool isTempDef = sqlConfig?.ResponseFieldTemp?.Field?.Params?.Count > 0;
            IEnumerable<SqlColumn> sqlColumnCommon = sqlConfig.ColumnsLst.Where<SqlColumn>(temp =>
            {
                return temp.TableId == sqlTable.Id && temp.AddPropertie != null
                         && temp.AddPropertie.DefaultValue != null
                         && (dictionaryUrl.ContainsKey(temp.AddPropertie.DefaultValue.ToString()) || isTempDef);
            });
            foreach (SqlColumn sqlColumn in sqlColumnCommon)
            {
                if (dicPK.ContainsKey(sqlColumn.Field)
                    && (Convert.IsDBNull(dicPK[sqlColumn.Field]) || dicPK[sqlColumn.Field] == null || sqlColumn.EditPropertie.IsUser == true || sqlColumn.EditPropertie.IsRequired == true))
                {
                    if (!string.IsNullOrEmpty(sqlColumn.AddPropertie?.DefaultValue?.ToString()) && dictionaryUrl.ContainsKey(sqlColumn.AddPropertie.DefaultValue.ToString()))
                    {
                        dicPK[sqlColumn.Field] = dictionaryUrl[sqlColumn.AddPropertie.DefaultValue.ToString()];
                    }
                }
            }

            //设置默认值来至内置参数
            if (sqlConfig.ResponseFieldTemp != null && sqlConfig.ResponseFieldTemp.Field?.Params != null)
            {
                IEnumerable<SqlColumn> sqlColumnCommonDef = sqlConfig.ColumnsLst.Where<SqlColumn>(temp =>
                {
                    return sqlConfig.ResponseFieldTemp.Field.Params.ContainsKey(temp.Field);
                });
                foreach (SqlColumn sqlColumn in sqlColumnCommonDef)
                {
                    if (ValidateUtil.IsNullOrEmptyOrDbNull(dicPK[sqlColumn.Field]))
                    {
                        dicPK[sqlColumn.Field] = sqlConfig.ResponseFieldTemp.Field.Params[sqlColumn.Field];
                    }
                }
            }
        }
  •  全局开启雪花算法

   /// <summary>
        /// 获取 主键ID信息
        /// </summary>
        /// <param name="ownerId"></param>
        /// <param name="sysId"></param>
        /// <param name="dictionaryUrl"></param>
        /// <param name="noGidSnowflake">是否禁用雪花算法获取ID</param>
        /// <returns></returns>
        public string GetDataGuid([RequiredStringPF("ownerId")] string ownerId, string sysId, Dictionary<string, object> dictionaryUrl, bool noGidSnowflake = false)
        {

            sysId = sysId ?? "sys";
              if (noGidSnowflake != true && _configuration.GetValue<bool>($"snowflake:{ownerId}:global"))
            {
                string machineIdI = _configuration.GetValue<string>($"snowflake:{ownerId}:machine")??"0";
                string datacenterId = _configuration.GetValue<string>($"snowflake:{ownerId}:{sysId}") ?? "-1";
                GidSnowflakeUtil GidSnowflakeUtil = new GidSnowflakeUtil(Convert.ToInt32(machineIdI), Convert.ToInt32(datacenterId));
                return GidSnowflakeUtil.GetId().ToString();
            }            else
            {
                string envId = EnvPFUtil.CurrentEnv();
                string guid = Guid.NewGuid().ToString();
                StringBuilder sbGuid = new StringBuilder();
                if (!string.IsNullOrEmpty(ownerId))
                {
                    sbGuid.Append($"{ownerId.Substring(0, ownerId.Length <= 4 ? ownerId.Length : 4)}-".ToLower());
                }
                if (!string.IsNullOrEmpty(envId))
                {
                    sbGuid.Append($"{envId.Substring(0, envId.Length <= 4 ? envId.Length : 4)}-".ToLower());
                }
                if (!string.IsNullOrEmpty(sysId) && sysId.Length > 16)
                {
                    sbGuid.Append($"{sysId.Substring(4, sysId.Length <= 8 ? sysId.Length : 8)}-");
                }
                else if (!string.IsNullOrEmpty(sysId))
                {
                    sbGuid.Append($"{sysId.Substring(0, sysId.Length <= 8 ? sysId.Length : 8)}-");
                }
                // 机器码  用于分布式扩展
                string machineId = _configuration.GetValue<string>("snowflake:machineId") ?? "";
                //处理字符串问题
                sbGuid.Replace("--", "-");
                return $"{machineId}-{sbGuid.ToString()}{guid.Substring(0, 36 - sbGuid.Length - machineId.Length - 1)}".Trim('-').PadRight(36, '0');
            }
        }
文档更新时间: 2022-09-18 13:25   作者:admin