Ctrip Apollo traditional .NET Configuration Center project integrated practice

There is the issue of official documents

Apollo may be due to the client source code distribution center has been in the update, resulting in its related documentation to keep up with the rhythm section of a document written by non-standard, it is easy to make docking novice friends misleading.

For example, I refer to the following two documents using traditional .NET client access to do when he found some problems.

  1. Two documents on identification of the application identity of AppIdan inconsistent configuration node.

  2. The second application configuration documentation for publishing environment of Environmentsignificant errors described configuration node.

Of course, these problems are likely to be repaired at any time. If you see does not match the content of the document described herein, please refer to the official documentation.

Traditional fast access .NET project

Quick to business.

Installation dependencies

In the infrastructure layer of your project by NuGet Package Manager or use the following command to add clients using traditional .NET project:

Install-Package Com.Ctrip.Framework.Apollo.ConfigurationManager -Version 2.0.3

What can be seen from the above package name? I have here is the optional 2.0.3version, more obvious is that this is a Javaer from the name.

Configure the application to identify & address service

In your startup project, open App.configor Web.configconfiguration file, <appSettings>add the following node node:

<!-- Change to the actual app id -->
<add key="Apollo.AppID" value="R01001" />
<add key="Apollo.MetaServer" value="http://localhost:8080" />

If you deploy multiple sets Config Service, supports multi-environment, please refer to the following configuration:

<!-- Change to the actual app id -->
<add key="Apollo.AppID" value="R01001" />

<!-- Should change the apollo config service url for each environment -->
<add key="Apollo.Env" value="DEV" />
<add key="Apollo.DEV.Meta" value="http://localhost:8080"/>
<add key="Apollo.FAT.Meta" value="http://localhost:8081"/>
<add key="Apollo.UAT.Meta" value="http://localhost:8082"/>
<add key="Apollo.PRO.Meta" value="http://localhost:8083"/>

Once configured, you are ready to use the Apollo projects of our clients in the.

Secondary package code

We used to use third-party libraries in a project when a layer of the package, this package is a shallow, generally do projects in the infrastructure layer, so there is no need to use other layers to introduce dependencies again.

Do not say, directly on the code.

Code structure is as follows:

├─MyCompany.MyProject.Infrastructure         # 项目基础设施层
│  │                                                       
│  └─Configuration                         
│          ApolloConfiguration.cs            # Apollo 分布式配置项读取实现     
│          ConfigurationChangeEventArgs.cs   # 配置更改回调事件参数
│          IConfiguration.cs                 # 配置抽象接口,可基于此接口实现本地配置读取

IConfiguration

using System;
using System.Configuration;

namespace MyCompany.MyProject.Infrastructure
{
    /// <summary>
    /// 配置抽象接口。
    /// </summary>
    public interface IConfiguration
    {
        /// <summary>
        /// 配置更改回调事件。
        /// </summary>
        event EventHandler<ConfigurationChangeEventArgs> ConfigChanged;

        /// <summary>
        /// 获取配置项。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="namespaces">命名空间集合</param>
        /// <returns></returns>
        string GetValue(string key, params string[] namespaces);

        /// <summary>
        /// 获取配置项。
        /// </summary>
        /// <typeparam name="TValue">值类型</typeparam>
        /// <param name="key">键</param>
        /// <param name="namespaces">命名空间集合</param>
        /// <returns></returns>
        TValue GetValue<TValue>(string key, params string[] namespaces);

        /// <summary>
        /// 获取配置项,如果值为 <see cref="null"/> 则取参数 <see cref="defaultValue"/> 值。
        /// </summary>
        /// <param name="key">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="namespaces">命名空间集合</param>
        /// <returns></returns>
        string GetDefaultValue(string key, string defaultValue, params string[] namespaces);

        /// <summary>
        /// 获取配置项,如果值为 <see cref="null"/> 则取参数 <see cref="defaultValue"/> 值。
        /// </summary>
        /// <typeparam name="TValue">值类型</typeparam>
        /// <param name="key">键</param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="namespaces">命名空间集合</param>
        /// <returns></returns>
        TValue GetDefaultValue<TValue>(string key, TValue defaultValue, params string[] namespaces);
    }
}

ConfigurationChangeEventArgs

using Com.Ctrip.Framework.Apollo.Model;
using System.Collections.Generic;

namespace MyCompany.MyProject.Infrastructure
{
    public class ConfigurationChangeEventArgs
    {
        public IEnumerable<string> ChangedKeys => Changes.Keys;
        public bool IsChanged(string key) => Changes.ContainsKey(key);
        public string Namespace { get; }
        public IReadOnlyDictionary<string, ConfigChange> Changes { get; }
        public ConfigurationChangeEventArgs(string namespaceName, IReadOnlyDictionary<string, ConfigChange> changes)
        {
            Namespace = namespaceName;
            Changes = changes;
        }
        public ConfigChange GetChange(string key)
        {
            Changes.TryGetValue(key, out var change);
            return change;
        }
    }
}

ApolloConfiguration

using System;
using System.Configuration;
using System.Globalization;
using Com.Ctrip.Framework.Apollo;
using Com.Ctrip.Framework.Apollo.Model;

namespace MyCompany.MyProject.Infrastructure
{
    public class ApolloConfiguration : IConfiguration
    {
        private readonly string _defaultValue = null;

        public event EventHandler<ConfigurationChangeEventArgs> ConfigChanged;

        private IConfig GetConfig(params string[] namespaces)
        {
            var config = namespaces == null || namespaces.Length == 0 ?
                ApolloConfigurationManager.GetAppConfig().GetAwaiter().GetResult() :
                ApolloConfigurationManager.GetConfig(namespaces).GetAwaiter().GetResult();

            config.ConfigChanged += (object sender, ConfigChangeEventArgs args) =>
            {
                ConfigChanged(sender, new ConfigurationChangeEventArgs(args.Namespace, args.Changes));
            };

            return config;
        }

        public string GetValue(string key, params string[] namespaces)
        {
            key = key ?? throw new ArgumentNullException(nameof(key));
            var config = GetConfig(namespaces);
            return config.GetProperty(key, _defaultValue);
        }

        public TValue GetValue<TValue>(string key, params string[] namespaces)
        {
            var value = GetValue(key, namespaces);
            return value == null ?
                default(TValue) :
                (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
        }

        public string GetDefaultValue(string key, string defaultValue, params string[] namespaces)
        {
            key = key ?? throw new ArgumentNullException(nameof(key));
            var config = GetConfig(namespaces);
            return config.GetProperty(key, defaultValue);
        }

        public TValue GetDefaultValue<TValue>(string key, TValue defaultValue, params string[] namespaces)
        {
            var value = GetDefaultValue(key, defaultValue, namespaces);
            return value == null ?
                default(TValue) :
                (TValue)Convert.ChangeType(value, typeof(TValue), CultureInfo.InvariantCulture);
        }
    }
}

Instructions

在使用之前需要先把ApolloConfiguration注册到应用容器中,请参考如下代码:

// 这里我们项目使用的 DI 框架是`Autofac`,按需修改吧,记得将实例注册成单例模式。
public class DependencyRegistrar : IDependencyRegistrar
{
    public void Register(ContainerBuilder builder, ITypeFinder typeFinder)
    {
        
        builder.RegisterType<ApolloConfiguration>()
            .As<IConfiguration>()
            .Named<IConfiguration>("configuration")
            .SingleInstance();
            
        ...
    }

    public int Order
    {
        get { return 1; }
    }
}

接下来就可以在项目中使用了,请参考如下代码:

public class UserController : BaseController
{
    private readonly IConfiguration _configuration;

    public UserController(IConfiguration configuration)
    {
        _configuration = configuration;
    }
    
    public ActionResult Add(AddUserInput model)
    {
        if (ModelState.IsValid)
        {
            // 从 Apollo 分布式配置中心 项目`R01001` 默认命名空间`application`下 读取配置项。
            model.Password = _configuration.GetValue("DefaultUserPassword");
            ...
        }
        ...
    }
}

Guess you like

Origin www.cnblogs.com/esofar/p/11310921.html