apolloconfig / apollo.net Goto Github PK
View Code? Open in Web Editor NEWApollo .Net Client
License: Apache License 2.0
Apollo .Net Client
License: Apache License 2.0
Base framework: .Net Core 2.1.2
Running environment: Centos 7 or ubuntu 18.04 、docker 18.06.0-ce
Exception
Unhandled Exception: System.InvalidOperationException: Failed to create instance of type 'Com.Ctrip.Framework.Apollo.ApolloOptions'. ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.TypeInitializationException: The type initializer for 'Com.Ctrip.Framework.Apollo.Foundation.NetworkInterfaceManager' threw an exception. ---> System.Net.Internals.SocketExceptionFactory+ExtendedSocketException: No such device or address
at System.Net.Dns.InternalGetHostByName(String hostName)
at System.Net.Dns.GetHostEntry(String hostNameOrAddress)
at Com.Ctrip.Framework.Apollo.Foundation.NetworkInterfaceManager.Refresh()
at Com.Ctrip.Framework.Apollo.Foundation.NetworkInterfaceManager..cctor()
--- End of inner exception stack trace ---
at Com.Ctrip.Framework.Apollo.Foundation.NetworkInterfaceManager.get_HostIp()
at Com.Ctrip.Framework.Apollo.ApolloOptions..ctor()
--- End of inner exception stack trace ---
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean wrapExceptions, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean wrapExceptions, Boolean skipCheckThis, Boolean fillCache)
at Microsoft.Extensions.Configuration.ConfigurationBinder.CreateInstance(Type type)
--- End of inner exception stack trace ---
at Microsoft.Extensions.Configuration.ConfigurationBinder.CreateInstance(Type type)
at Microsoft.Extensions.Configuration.ConfigurationBinder.BindInstance(Type type, Object instance, IConfiguration config, BinderOptions options)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get(IConfiguration configuration, Type type, Action`1 configureOptions)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration, Action`1 configureOptions)
at Microsoft.Extensions.Configuration.ConfigurationBinder.Get[T](IConfiguration configuration)
at FabricDemo.UserService.Program.<>c.<CreateWebHostBuilder>b__1_0(WebHostBuilderContext hostingContext, IConfigurationBuilder builder) in /src/src/FabricDemo.UserService/Program.cs:line 25
at Microsoft.AspNetCore.Hosting.WebHostBuilder.BuildCommonServices(AggregateException& hostingStartupErrors)
at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
at FabricDemo.UserService.Program.Main(String[] args) in /src/src/FabricDemo.UserService/Program.cs:line 15
{
"apollo": {
"AppId": "FabricDemo.UserService",
"MetaServer": "http://pro.meta-server.zengql.local"
}
}
/// <inheritdoc />
public class Program
{
/// <inheritdoc />
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
/// <inheritdoc />
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration(
(hostingContext, builder) =>
{
builder.AddApollo(builder.Build().GetSection("apollo"))
.AddDefault()
.AddNamespace("TEST1.ConsulPublic");
})
.UseStartup<Startup>();
}
FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 54045
FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY src/FabricDemo.UserService/FabricDemo.UserService.csproj src/FabricDemo.UserService/
RUN dotnet restore src/FabricDemo.UserService/FabricDemo.UserService.csproj
COPY . .
WORKDIR /src/src/FabricDemo.UserService
RUN dotnet build FabricDemo.UserService.csproj -c Release -o /app
FROM build AS publish
RUN dotnet publish FabricDemo.UserService.csproj -c Release -o /app
FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "FabricDemo.UserService.dll"]
version: '3'
services:
userservice:
container_name: userservice
image: fabricdemo/userservice:${TAG:-latest}
build:
context: .
dockerfile: src/FabricDemo.UserService/Dockerfile
network_mode: host
restart: always
environment:
- ASPNETCORE_ENVIRONMENT=Development
- ASPNETCORE_URLS=http://127.0.0.1:54045
ports:
- "54045:54045"
Start command: docker-compose up --build
Please give a solution, thanks!
看多数demo都是直接注入IConfiguration使用的.我想使用强类型的Options,不知道这方面支持怎么样.
单例的IOptions<TOptions>
是肯定可以的,IOptionsMonitor<TOptions>
呢?
1、我们公司因为命名空间比较多,所以用了AddNameSpace方法,然后发现每次都会触发StartLongPolling方法建立长连接,每台服务器常年保持TCP链接数在1.2万,多了以后会导致阿波罗资源耗尽,
2、java客户端RemoteConfigLongPollService用的是单例,但是在.net客户端中每次都new 一个。
麻烦大佬看看是否真的有问题,能否优化~
我同一个程序在本地是可以得到配置信息的,但把程序移到另一台服务器后就提示请求超时了
[Warn] Long polling failed, will retry in 120 seconds. appId: parttask, cluster: dev, names
pace: application, long polling url: , reason: Get config services failed from http://192.168.5.141:
8080//services/config?appId=parttask&ip=192.168.5.244 [Cause: Could not complete get operation [Caus
e: 操作已超时。]]
实例中95是我本地的客户端
想问一下我可以从什么方面检查是什么问题导致请求不到配置
原来的使用文档已经不适用了,麻烦更新文档内容
大佬要不要考虑一下用稍微低一些的 LangVersion,绝大多数不会选择使用preview。☺
preview
using var httpClient = client.CreateHttpClient();
apollo配置系统很不错,这个.net sdk有没有支持.NETStandard的时间安排,更好的支持.net core
您好,我有一个.Net Core的应用,配置中心是Apollo的,有一个疑问,就是当.Net应用第一次启动
时(本地没有Apollo的配置文件),由于某些原因.Net客户端和Apollo服务器网络是不通的,此时.Net
应用和Apollo无法建立长连接,也无法加载Apollo的配置。然后过一会网络通了,
.Net Core的应用所在的环境也能和Apollo通了,但是Apollo的客户端不会尝试重连Apollo,
也就是当应用第一次启动时,无法没有成功连接Apollo,就不会再次重连,
导致应用无法加载配置,请问这种问题是我配置的问题,
还是Apollo客户端有什么配置可以让Apollo客户端一直重连Apollo服务器?
.NetCore版本为2.1
Apollo客户端1.3.1
.net core 客户端能否把日志加上呢?没有日志太不方便了
不太清楚.net如何使用热发布的功能
请问如果namespace是txt类型,我想单纯读取整个文本,该用什么方法实现呢
在同步方法中调用异步方法,不管怎么尝试,在高负载的情况下还是会引起死锁,下面是我的测试代码
namespace AsyncTestConsoleApp
{
class Program
{
private static readonly TaskFactory MyTaskFactory = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default);
private static void RunSync(Func<Task> func)
{
var cultureUi = CultureInfo.CurrentUICulture;
var culture = CultureInfo.CurrentCulture;
MyTaskFactory.StartNew(() =>
{
Thread.CurrentThread.CurrentCulture = culture;
Thread.CurrentThread.CurrentUICulture = cultureUi;
return func();
}).Unwrap().GetAwaiter().GetResult();
}
public static void PrintThreadLog(string title)
{
if (string.IsNullOrWhiteSpace(title))
{
title = "默认";
}
ThreadPool.GetMinThreads(out var minWorker0, out var minIOC0);
ThreadPool.GetMaxThreads(out var maxWorker0, out var maxIOC0);
ThreadPool.GetAvailableThreads(out var aWorkerThreads, out var aCompletionPortThreads);
Console.WriteLine($"{title}:minWorker:{minWorker0} minIOC:{minIOC0}");
Console.WriteLine($"{title}:maxWorker:{maxWorker0} maxIOC:{maxIOC0}");
Console.WriteLine($"{title}:AvailableWorker:{maxWorker0} AvailablemaxCompletionPortThreads:{maxIOC0}");
}
static void Main(string[] args)
{
ThreadPool.SetMinThreads(2, 200);
ThreadPool.SetMaxThreads(5, 200);
PrintThreadLog("");
IConnection connection = new Connection(new User());
int waitingStart = 0, inProgress = 0;
int sleepTime = 150;
int waited = 0;
for (; ; )
{
Interlocked.Increment(ref waitingStart);
// 模拟客户端请求
// assume IConnection interface can't be changed to async
ThreadPool.QueueUserWorkItem(
_ =>
{
Interlocked.Decrement(ref waitingStart);
Interlocked.Increment(ref inProgress);
//await connection.OnRequestReceivedAsync("request");
connection.OnRequestReceived("request");
Interlocked.Decrement(ref inProgress);
});
string msg = string.Format(
"Requests in queue: {0}, requests in progress: {1}, current sleep time: {2}",
Volatile.Read(ref waitingStart),
Volatile.Read(ref inProgress),
Volatile.Read(ref sleepTime));
bool poolAlive = CheckPoolAlive();
if (waited > 500 || !poolAlive)
{
Console.Clear();
Console.WriteLine(msg);
waited = 0;
}
if (!poolAlive)
throw new InvalidOperationException("ThreadPool deadlocked! " + msg);
if (sleepTime > 30) sleepTime--;
Thread.Sleep(sleepTime);
waited += sleepTime;
}
}
static bool CheckPoolAlive()
{
// very simple check for ThreadPool deadlock
// during this check no new requests will be enqueued
// failing this check means that all current executing requests will never finish
using (ManualResetEventSlim ok = new ManualResetEventSlim(false))
{
ThreadPool.QueueUserWorkItem(_ => ok.Set());
return ok.Wait(30000);
}
}
interface IConnection
{
void OnRequestReceived(string request);
Task OnRequestReceivedAsync(string request);
}
class Connection : IConnection
{
readonly User _user;
public Connection(User user)
{
_user = user;
}
public void OnRequestReceived(string request)
{
// 同步调用异步
//var task = _user.HandleRequest(request);
RunSync(()=> _user.HandleRequest(request));
//task.Wait();
//tas
//task.GetAwaiter().GetResult();
//if (!task.Result) throw new InvalidOperationException();
}
public async Task OnRequestReceivedAsync(string request)
{
// 同步调用异步
var task = await _user.HandleRequest(request);
if (!task) throw new InvalidOperationException();
}
}
class User
{
public async Task<bool> HandleRequest(string request)
{
//下面这句会把当前控制权交给调用者
await Task.Delay(Rnd.Next(30, 700)); // 模拟各种操作
return true;
}
}
[ThreadStatic]
static Random _rnd;
static Random Rnd => _rnd ?? (_rnd = new Random(Guid.NewGuid().GetHashCode()));
}
}
所以,作为一个标杆项目,在代码中出现同步方法调用异步的是不是不太合适,谢谢!
net461下Apollo配置能不能直接序列化对象,这里的配置可以是全部,也可以是其中的一部分。类似于JsonConvert.SerializeObject();
在framework 下加载多个命名空间时,会出现获取配置信息的网络请求超时,导致c盘配置文件无法创建,配置变更后也无法及时收到通知。
提示:Could not complete get operation [Cause: The operation has timed out ]
设置Apollo.Timeout,Apollo.ReadTimeout也无法解决。
我看了net core一些源码,里面实现了ApolloConfigurationBuilder可实现appsetting的一些配置的转移,项目的相关配置信息会保存两份,一份在Apollo里,一份在实现的IConfigurationSource的Data里,这样是否会有资源浪费?
core分支,参见Apollo.AspNet.Demo中,采用在web.config中配置的方式,当配置中心发布配置后,客户端收到了最新配置,opt中的配置文件也是最新的,但是通过ConfigurationManager.AppSettings获取的配置还是旧的。看到源码中ApolloConfigurationBuilder类private void Config_ConfigChanged(object sender, ConfigChangeEventArgs args) => ConfigurationManager.RefreshSection(SectionName); 该事件有触发,但是并没有触发AppSettingsSectionBuilder类的ProcessConfigurationSection来刷新配置
Configuration.GetValue("ApNames")返回数据是null,我确认已经在web上设置值了的
自动生成了C:\opt\data\baidu\config-cache文件夹,但是文件夹里面是空的。
客户端有debug功能吗?可以打印日志信息吗?现在有问题都无从查起。
你好,从监控数据来看,apollo 客户端每隔一分钟就会向eureka服务器端请求最新的配置,如果没有是返回304.我的疑问是,配置了refreshinterval,但是并没有起到作用。并且和原本代码里注明的5min不太一样。能否给解答一下呢?谢谢
请发布Nuget包时别移除之前的版本,如果你发的包不稳定,请用alpha版本或者beta版本。不然影响项目开发
有包含开放平台操作Apollo服务的请求api吗
{ "Apollo": { "AppId": "netcore", "MetaServer": "http://10.2.2.139:8080", "Env": "Pro", "ConfigServer": [ "http://10.2.2.140:8080/" ] } }
配置如上,但是获取的配置还是DEV的。Env节点不起作用
建议在Apollo\Util\Http\HttpUtil.cs文件的Task<HttpResponse> DoGetAsync(string url, int timeout)方法中加上签名的功能,或者扩展出增加Request Header的选项吧
如题
paas服务出口ip太多了,配置服务器添加白名单很麻烦,能否在请求配置服务器的时候主动使用代理来访问呢。
目前程序使用appId和MetaServer这两个字段就可以获取到配置信息了,而Env字段没起到相应的作用。
能否参照 .net framework的多种环境配置方式,将多环境的meta 都一起写入,然后通过修改env的值来选择相应的meta呢?
场景:在使用apollo.net 客户端的时候,如ConfigService 挂了,在这期间使用portal发布新的配置(提示发布成功,实例列表会提示应用使用非最新的配置),重新启用ConfigService,等待服务正常,但是客户端拉取后依旧没有更新到最新的配置,但是portal 实例列表提示以及使用最新的配置了;
问题所在:客户端在执行拉取任务中,在执行GetConfig()时,会先判断_syncException,如果有异常就会直接抛出,如下图:
所以在ConfigService 挂掉,再重新启动这个_syncException 异常没有及时的清除,查找了一下,看到(如下图)
这里在同步配置的时候没有及时的清除_syncException,导致更新不了
结果:我尝试及时的清除_syncException,表现正常,希望能尽快解决整个问题(不知道java客户端是否也有整个问题);
https://www.cnblogs.com/dudu/p/6251266.html
这是关于同步里面调用异步方法产生死锁的现象
如图,将 key aaa 从 aoaoao... 更新 为 aoao 后,
Configuration[key].value:aoaoao....,AppSetting[key].value:aoao
Global 配置如下
public class WebApiApplication : System.Web.HttpApplication
{
public static IConfiguration Configuration { get; private set; }
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
Configuration = new Microsoft.Extensions.Configuration.ConfigurationBuilder()
.AddApollo(ConfigurationManager.AppSettings["Apollo.AppId"], ConfigurationManager.AppSettings["Apollo.MetaServer"])
.AddDefault()
.Build();
}
}
Web.config 配置如下
<configSections> <section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /> </configSections> <configBuilders> <builders> <add name="AppSettingsSectionBuilder" type="Com.Ctrip.Framework.Apollo.AppSettingsSectionBuilder, Com.Ctrip.Framework.Apollo.ConfigurationManager" /> <add name="ConnectionStringsSectionBuilder" type="Com.Ctrip.Framework.Apollo.ConnectionStringsSectionBuilder, Com.Ctrip.Framework.Apollo.ConfigurationManager" /> </builders> </configBuilders> <connectionStrings configBuilders="ConnectionStringsSectionBuilder" /> <appSettings configBuilders="AppSettingsSectionBuilder"> <add key="Apollo.AppId" value="sunnytest" /> <add key="Apollo.Timeout" value="5000" /> <add key="Apollo.RefreshInterval" value="3000" /> <add key="Apollo.Env" value="Dev" /> <add key="Apollo.MetaServer" value="http://192.168.5.133:8080/" /> <add key="Apollo.ConfigServer" value="http://192.168.5.133:8080/" /> </appSettings>
获取代码如下
[HttpGet]
[Route("api/Apollo/Section/{key}")]
public async Task Section(string key)
{
var config = WebApiApplication.Configuration;
//await ApolloConfigurationManager.GetAppConfig();
if (string.IsNullOrEmpty(key))
return await Task.FromResult<string>(null);
var value = config[key];
var value2 = ConfigurationManager.AppSettings[key];
return await Task.FromResult($"{nameof(key)}:{key},Configuration[key].value:{value},AppSetting[key].value:{value2}");
}
现在.net core SDK配置的value值只是字符串,如果要支持JSON、XML等特定格式,有什么好的实现方法?
手里有一个.net core api的项目,情况是这样的:
在没有使用阿波罗配置的时候 这个项目占用的内存基本是在50M左右的,一旦启用了阿波罗配置,并且访问之后每次访问差不多都能增加1M左右的内存使用而没有使用阿波罗则没有这种情况
我司想采用归司的配置中心,但是当前所有的业务系统均采用asp.net core,正打算阅读源码改成支持asp.net core。
.net 版本是否支持 敏感信息加密?
Application startup exception
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Collections.Generic.HashSet`1.AddIfNotPresent(T value)
at System.Collections.Generic.HashSet`1.Add(T item)
at Com.Ctrip.Framework.Apollo.Internals.RemoteConfigLongPollService.Submit(String namespaceName, RemoteConfigRepository remoteConfigRepository)
Aborted (core dumped)
at Com.Ctrip.Framework.Apollo.Inte
如上是错误信息,使用的是.net core客户端,下面是错误行
ApolloConfigurationManager apolloConfigurationManager = new ApolloConfigurationManager();
apolloConfigurationManager.GetConfig("application").ConfigureAwait(true).GetAwaiter().GetResult().ConfigChanged += OnDatabaseChanged;
原代码:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((cotnext, builder) =>
{
// cotnext.Configuration.GetSection("apollo") 读取不到
builder.AddApollo(cotnext.Configuration.GetSection("apollo"))
.AddDefault(ConfigFileFormat.Xml)
.AddDefault(ConfigFileFormat.Json)
.AddDefault(ConfigFileFormat.Yml)
.AddDefault(ConfigFileFormat.Yaml)
.AddDefault();
})
.UseStartup();
修改后代码:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((cotnext, builder) =>
{
// builder.Build().GetSection("apollo") 可以读取
builder.AddApollo(builder.Build().GetSection("apollo"))
.AddDefault(ConfigFileFormat.Xml)
.AddDefault(ConfigFileFormat.Json)
.AddDefault(ConfigFileFormat.Yml)
.AddDefault(ConfigFileFormat.Yaml)
.AddDefault();
})
.UseStartup();
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.