.net core 读取Apollo配置

在网上找了很多读取Apollo配置,很多都只有讲如何搭建Apollo以及Apollo应用中心使用,但是没有详细的.net core读取配置方式,自己总结了一下,在网上与各位.net开发小伙伴分享。

一、Apollo应用中心搭建及使用。

首先本地搭建Apollo,请参照官网资料https://github.com/ctripcorp/apollo/wiki/Quick-Start。

进入Apollo的管理UI,创建项目:

创建项目后,就可以在项目中添加Key、value了:

添加key后,需要发布才能生效。

二、代码应用:

创建.net core项目,修改Program.cs中的代码:

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .ConfigureAppConfiguration(builder =>
            {
                //这里的方法目的是使用Apollo读取配置
                builder.AddEnvironmentVariables().AddApollo(builder.Build().GetSection("apollo"))
                    .AddDefault()
                    .AddNamespace("Common");//Apollo中NameSpace的名称,可不使用;
            }
            )
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

appsettings.json文件增加Apollo配置:

/*这里是添加Apollo配置*/
  "apollo": {
    "AppId": "1000000",   /*Apollo配置的Appid*/
    "Env": "Dev",
    "MetaServer": "http://config.k8s.test.net/",   /*CI/CD地址*/
    "cluster": "default"    /*集群名称*/
  }

使用代码:

/// <summary>
    /// Apollo配置文件
    /// </summary>
    public static class Configs
    {
        /// <summary> 数据库连接字符串配置Key </summary>
        public static string SqlConnectStr => ApolloConfigUtil.GetAppSetting("SqlConnectStr");    //这里的SqlConnectStr是Apollo配置中的Key

    }



using Com.Ctrip.Framework.Apollo;
using Microsoft.Extensions.Configuration;
using System;


 /// <summary>
    /// 阿波罗工具类
    /// </summary>
    public static class ApolloConfigUtil
    {
        //
        // 摘要:
        //     配置
        private static readonly IConfiguration Configuration = CreateConfiguration();

        //
        // 摘要:
        //     生成配置方法
        private static IConfiguration CreateConfiguration()
        {
            IConfigurationBuilder configurationBuilder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
            configurationBuilder.AddEnvironmentVariables();
            IApolloConfigurationBuilder builder = configurationBuilder.AddApollo(configurationBuilder.Build().GetSection("apollo")).AddDefault();
            string value = configurationBuilder.Build().GetValue("Apollo.NameSpaces", string.Empty);
            if (value.IsNullOrEmpty())
            {
                throw new ArgumentException("未配置Apollo.NameSpaces");
            }

            string[] array = value.Split(new char[1]
            {
                ','
            });
            foreach (string text in array)
            {
                if (text != "application")
                {
                    builder.AddNamespace(text);
                }
            }

            return configurationBuilder.Build();
        }

        //
        // 摘要:
        //     根据配置节名称获取配置节
        //
        // 参数:
        //   sectionName:
        //
        // 类型参数:
        //   T:
        public static T GetSection<T>(string sectionName) where T : class
        {
            try
            {
                string value = Configuration.GetValue(sectionName, string.Empty);
                return (value != null) ? value.ToObject<T>() : null;
            }
            catch
            {
            }

            return null;
        }

        //
        // 摘要:
        //     根据key获取配置内容
        //
        // 参数:
        //   key:
        public static string GetAppSetting(string key)
        {
            try
            {
                return Configuration.GetValue(key, string.Empty);
            }
            catch
            {
            }

            return string.Empty;
        }
    }
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;


//
    // 摘要:
    //     Json工具类
    //
    // 言论:
    public static class JsonUtil
    {
        //
        // 摘要:
        //     Json序列化
        //
        // 参数:
        //   source:
        //     需要序列化对象
        //
        // 返回结果:
        //     Json字符串
        public static string ToJson(this object source)
        {
            if (!(source is string))
            {
                return JsonConvert.SerializeObject(source);
            }

            return source.ToString();
        }

        //
        // 摘要:
        //     Json反序列化
        //
        // 参数:
        //   obj:
        //     Json字符串
        //
        // 类型参数:
        //   T:
        //     返回类型
        public static T ToObject<T>(this string obj) where T : class
        {
            if (string.IsNullOrWhiteSpace(obj))
            {
                return null;
            }

            if (typeof(T) == typeof(string))
            {
                return obj as T;
            }

            return (T)JsonConvert.DeserializeObject(obj, typeof(T));
        }

        //
        // 摘要:
        //     Json反序列化
        //
        // 参数:
        //   jsonString:
        //     Json字符串
        //
        //   errorHandler:
        //     反序列化过程中的异常处理
        //
        // 类型参数:
        //   T:
        //     返回类型
        //
        // 返回结果:
        //     返回对象
        public static T ToObject<T>(this string jsonString, Action<Exception> errorHandler) where T : class
        {
            if (string.IsNullOrEmpty(jsonString))
            {
                return null;
            }

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                Error = delegate (object obj, Newtonsoft.Json.Serialization.ErrorEventArgs args)
                {
                    args.ErrorContext.Handled = true;
                    errorHandler?.Invoke(args.ErrorContext.Error);
                }
            };
            return JsonConvert.DeserializeObject<T>(jsonString, settings);
        }

        //
        // 摘要:
        //     解析JSON生成对象实体集合
        //
        // 参数:
        //   json:
        //     json字符串
        //
        // 类型参数:
        //   T:
        //     对象类型
        //
        // 返回结果:
        //     返回对象list
        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        {
            try
            {
                return JsonConvert.DeserializeObject<List<T>>(json);
            }
            catch
            {
                JsonSerializer jsonSerializer = new JsonSerializer();
                StringReader reader = new StringReader(json);
                return jsonSerializer.Deserialize(new JsonTextReader(reader), typeof(List<T>)) as List<T>;
            }
        }

        //
        // 摘要:
        //     反序列化JSON到给定的匿名对象.
        //
        // 参数:
        //   json:
        //     json字符串
        //
        //   anonymousTypeObject:
        //     匿名对象
        //
        // 类型参数:
        //   T:
        //     匿名对象类型
        //
        // 返回结果:
        //     匿名对象
        public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
        {
            return JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
        }

        //
        // 摘要:
        //     Json反序列化
        //
        // 参数:
        //   jsonString:
        //
        //   type:
        public static object ToObject(string jsonString, Type type)
        {
            return JsonConvert.DeserializeObject(jsonString, type);
        }
    }
using System;
using System.Text.RegularExpressions;


//
    // 摘要:
    //     字符串扩展方法
    //
    // 言论:
    public static class StringExtension
    {
        //
        // 摘要:
        //     验证下拉框,值为空,0,请选择则返回false
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool DropDown(this string value)
        {
            if (!string.IsNullOrEmpty(value) && value != "0")
            {
                return value != "请选择";
            }

            return false;
        }

        //
        // 摘要:
        //     验证邮箱
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool Email(this string value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value, "^\\w+(\\.\\w*)*@\\w+\\.\\w+$");
            }

            return false;
        }

        //
        // 摘要:
        //     验证手机
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool IsMobile(this string value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value, "^([0\\+]\\d{2,3}-)?(1[3|4|5|6|7|8|9]\\d{9})$");
            }

            return false;
        }

        //
        // 摘要:
        //     验证日期
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool IsDateTime(this string value)
        {
            try
            {
                DateTime result;
                return DateTime.TryParse(value, out result);
            }
            catch (Exception)
            {
                return false;
            }
        }

        //
        // 摘要:
        //     只允许输入英文字母或数字
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool EngNum(this string value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value, "^[0-9a-zA-Z]*$");
            }

            return false;
        }

        //
        // 摘要:
        //     只允许汉字、英文字母或数字
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool ChsEngNum(this string value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value, "^([\\u4E00-\\uFA29]|[\\uE7C7-\\uE7F3]|[a-zA-Z0-9])*$");
            }

            return false;
        }

        //
        // 摘要:
        //     最小长度
        //
        // 参数:
        //   value:
        //     值
        //
        //   min:
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool MinLength(this string value, int min)
        {
            if (value != null)
            {
                return value.Trim().Length >= min;
            }

            return false;
        }

        //
        // 摘要:
        //     最大长度
        //
        // 参数:
        //   value:
        //     值
        //
        //   max:
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool MaxLength(this string value, int max)
        {
            if (value != null)
            {
                return value.Trim().Length <= max;
            }

            return false;
        }

        //
        // 摘要:
        //     整数
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool Digits(this string value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value, "^\\d+$");
            }

            return false;
        }

        //
        // 摘要:
        //     范围
        //
        // 参数:
        //   value:
        //     值
        //
        //   min:
        //
        //   max:
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool Range(this string value, int min, int max)
        {
            if (value == null)
            {
                return false;
            }

            int length = value.Length;
            if (length >= min)
            {
                return length <= max;
            }

            return false;
        }

        //
        // 摘要:
        //     数字
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool Number(this string value)
        {
            if (value != null)
            {
                return Regex.IsMatch(value, "^-?(?:\\d+|\\d{1,3}(?:,\\d{3})+)(?:\\.\\d+)?$");
            }

            return false;
        }

        //
        // 摘要:
        //     不能为空
        //
        // 参数:
        //   value:
        //     值
        //
        // 返回结果:
        //     返回bool
        //
        // 言论:
        public static bool Required(this string value)
        {
            if (value != null)
            {
                return !value.IsNullOrEmpty();
            }

            return false;
        }

        //
        // 摘要:
        //     判断字符串是否为空
        //
        // 参数:
        //   value:
        //
        // 言论:
        public static bool IsNullOrEmpty(this string value)
        {
            if (value != null)
            {
                return string.IsNullOrEmpty(value.Trim());
            }

            return true;
        }

        //
        // 摘要:
        //     检查指定的字符串是否为有效的日期格式{yyyy-M(M)-d(d) H(H):m(m):s(s)},年份暂定位在[1900,2100),
        //
        // 参数:
        //   dateString:
        //     日期字符串
        //
        //   longDateFormat:
        //     是否为长日期格式
        public static bool ValidDate(this string dateString, bool longDateFormat)
        {
            if (string.IsNullOrEmpty(dateString))
            {
                return false;
            }

            string[] array = dateString.Split(new char[1]
            {
                ' '
            });
            if (longDateFormat)
            {
                if (array.Length != 2)
                {
                    return false;
                }

                if (!Regex.IsMatch(array[1], "^(([01]?[0-9])|(2[0-3]))(\\:[0-5]?[0-9]){2}$"))
                {
                    return false;
                }
            }

            Match match = Regex.Match(array[0], "^(?<yyyy>((19)|(20))[0-9]{2})-(?<M>((0?[1-9])|(1[012])))-(?<d>((0?[1-9])|([12][0-9])|(3[01])))$");
            if (!match.Success)
            {
                return false;
            }

            int year = int.Parse(match.Groups["yyyy"].Value);
            int month = int.Parse(match.Groups["M"].Value);
            int num = int.Parse(match.Groups["d"].Value);
            return DateTime.DaysInMonth(year, month) >= num;
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值