- 安装依赖包
bash
> Com.Ctrip.Framework.Apollo 2.10.0 2.10.0
> Com.Ctrip.Framework.Apollo.ConfigAdapter.Yaml 2.9.0 2.9.0
> Com.Ctrip.Framework.Apollo.Configuration 2.10.2 2.10.2
> Com.Ctrip.Framework.Apollo.ExtensionsHosting 2.10.1 2.10.1
- 修改appsettings.json
bash
"Apollo": {
"AppId": "ellis",
"Env": "DEV",
"MetaServer": "http://192.168.214.133:30080",
"ConfigServer": [ "http://192.168.214.133:30080" ],
}
- 添加配置类
csharp
using Com.Ctrip.Framework.Apollo.Internals;
using Microsoft.Extensions.Primitives;
namespace CoreApollo
{
public class MyConfigService
{
private readonly IConfiguration _configuration;
public static Dictionary<string,string> configDictionary = new Dictionary<string, string>();
public static object lockobj = new object();
public MyConfigService(IConfiguration configuration)
{
_configuration = configuration;
// 监听配置变更
ChangeToken.OnChange(() => _configuration.GetReloadToken(), OnConfigChanged);
}
public string GetConfig(string key)
{
return _configuration[key];
}
private void OnConfigChanged()
{
Console.WriteLine("Apollo configuration has changed!");
lock(lockobj)
{
foreach (var section in _configuration.AsEnumerable())
{
configDictionary[section.Key] = section.Value;
}
}
Console.WriteLine("re init");
}
}
}
- 依赖注入
csharp
using Com.Ctrip.Framework.Apollo;
using CoreApollo;
//YamlConfigAdapter.Register();
var builder = WebApplication.CreateBuilder(args);
builder.Configuration
.AddApollo(builder.Configuration.GetSection("Apollo"))
.AddDefault();
builder.Services.AddScoped<MyConfigService>();
- controller
csharp
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace CoreApollo.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ApolloController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly MyConfigService _myConfigService;
public ApolloController(IConfiguration configuration, MyConfigService myConfigService)
{
_configuration = configuration;
_myConfigService = myConfigService;
}
[HttpGet]
public IActionResult GetConfig(string key)
{
var myConfigValue = _myConfigService.GetConfig(key);
return Ok(myConfigValue);
}
}
}
https://www.apolloconfig.com/#/zh/client/dotnet-sdk-user-guide