THIS IS A TEST INSTANCE ONLY! REPOSITORIES CAN BE DELETED AT ANY TIME!

Browse Source

🎉 Initial commit.

pull/3/head
catcherwong 1 year ago
parent
commit
892a5e792a
  1. 46
      .github/workflows/build.yml
  2. 333
      .gitignore
  3. 20
      Directory.Build.props
  4. 186
      README.md
  5. 185
      README.zh-cn.md
  6. 79
      _stylecop/codeanalysis.ruleset
  7. 5
      build/version.props
  8. BIN
      media/prj.png
  9. 101
      nacos-sdk-csharp.sln
  10. 10
      samples/App1/App1.csproj
  11. 46
      samples/App1/Controllers/ValuesController.cs
  12. 18
      samples/App1/Program.cs
  13. 41
      samples/App1/Startup.cs
  14. 9
      samples/App1/appsettings.Development.json
  15. 15
      samples/App1/appsettings.json
  16. 10
      samples/App2/App2.csproj
  17. 46
      samples/App2/Controllers/ValuesController.cs
  18. 18
      samples/App2/Program.cs
  19. 41
      samples/App2/Startup.cs
  20. 9
      samples/App2/appsettings.Development.json
  21. 15
      samples/App2/appsettings.json
  22. 11
      samples/App3/App3.csproj
  23. 46
      samples/App3/Controllers/ValuesController.cs
  24. 20
      samples/App3/Program.cs
  25. 41
      samples/App3/Startup.cs
  26. 9
      samples/App3/appsettings.Development.json
  27. 17
      samples/App3/appsettings.json
  28. 32
      samples/MsConfigApp/AppSettings.cs
  29. 62
      samples/MsConfigApp/Controllers/ConfigController.cs
  30. 17
      samples/MsConfigApp/MsConfigApp.csproj
  31. 79
      samples/MsConfigApp/Program.cs
  32. 41
      samples/MsConfigApp/Startup.cs
  33. 9
      samples/MsConfigApp/SubObj.cs
  34. 16
      samples/MsConfigApp/appsettings.json
  35. 9
      src/Nacos.AspNetCore/INacosServerManager.cs
  36. 19
      src/Nacos.AspNetCore/LoadBalance/ILBStrategy.cs
  37. 20
      src/Nacos.AspNetCore/LoadBalance/LBStrategyName.cs
  38. 46
      src/Nacos.AspNetCore/LoadBalance/WeightRandomLBStrategy.cs
  39. 34
      src/Nacos.AspNetCore/LoadBalance/WeightRoundRobinLBStrategy.cs
  40. 38
      src/Nacos.AspNetCore/Nacos.AspNetCore.csproj
  41. 66
      src/Nacos.AspNetCore/NacosAspNetCoreOptions.cs
  42. 9
      src/Nacos.AspNetCore/NacosServer.cs
  43. 67
      src/Nacos.AspNetCore/NacosServerManager.cs
  44. 80
      src/Nacos.AspNetCore/ServiceCollectionExtensions.cs
  45. 231
      src/Nacos.AspNetCore/StatusReportBgTask.cs
  46. 9
      src/Nacos.Microsoft.Extensions.Configuration/INacosConfigurationParser.cs
  47. 122
      src/Nacos.Microsoft.Extensions.Configuration/Impl/MsConfigServerHttpAgent.cs
  48. 36
      src/Nacos.Microsoft.Extensions.Configuration/Impl/NacosMsConfigClient.cs
  49. 123
      src/Nacos.Microsoft.Extensions.Configuration/JsonConfigurationStringParser.cs
  50. 39
      src/Nacos.Microsoft.Extensions.Configuration/Nacos.Microsoft.Extensions.Configuration.csproj
  51. 60
      src/Nacos.Microsoft.Extensions.Configuration/NacosConfigurationExtensions.cs
  52. 91
      src/Nacos.Microsoft.Extensions.Configuration/NacosConfigurationProvider.cs
  53. 82
      src/Nacos.Microsoft.Extensions.Configuration/NacosConfigurationSource.cs
  54. 18
      src/Nacos/Common/BaseRequest.cs
  55. 97
      src/Nacos/Common/ConstValue.cs
  56. 53
      src/Nacos/Common/NacosOptions.cs
  57. 24
      src/Nacos/Common/RequestPathValue.cs
  58. 304
      src/Nacos/Config/AbstNacosConfigClient.cs
  59. 17
      src/Nacos/Config/Core/Listener.cs
  60. 102
      src/Nacos/Config/Failover/FileLocalConfigInfoProcessor.cs
  61. 13
      src/Nacos/Config/Failover/ILocalConfigInfoProcessor.cs
  62. 54
      src/Nacos/Config/Failover/MemoryLocalConfigInfoProcessor.cs
  63. 32
      src/Nacos/Config/Http/HttpAgent.cs
  64. 65
      src/Nacos/Config/Http/HttpAgentCommon.cs
  65. 54
      src/Nacos/Config/Http/IHttpAgent.cs
  66. 124
      src/Nacos/Config/Http/ServerHttpAgent.cs
  67. 37
      src/Nacos/Config/NacosConfigClient.cs
  68. 67
      src/Nacos/Config/Requests/AddListenerRequest.cs
  69. 45
      src/Nacos/Config/Requests/GetConfigRequest.cs
  70. 52
      src/Nacos/Config/Requests/ListenerConfigRequest.cs
  71. 73
      src/Nacos/Config/Requests/PublishConfigRequest.cs
  72. 42
      src/Nacos/Config/Requests/RemoveConfigRequest.cs
  73. 40
      src/Nacos/Config/Requests/RemoveListenerRequest.cs
  74. 252
      src/Nacos/Config/ServerListManager.cs
  75. 189
      src/Nacos/DependencyInjection/ServiceCollectionExtensions.cs
  76. 24
      src/Nacos/Exceptions/NacosException.cs
  77. 46
      src/Nacos/INacosConfigClient.cs
  78. 138
      src/Nacos/INacosNamingClient.cs
  79. 35
      src/Nacos/Nacos.csproj
  80. 308
      src/Nacos/Naming/Http/NamingProxy.cs
  81. 450
      src/Nacos/Naming/NacosNamingClient.cs
  82. 69
      src/Nacos/Naming/Requests/CreateServiceRequest.cs
  83. 81
      src/Nacos/Naming/Requests/GetInstanceRequest.cs
  84. 44
      src/Nacos/Naming/Requests/GetServiceRequest.cs
  85. 26
      src/Nacos/Naming/Requests/ListClusterServersRequest.cs
  86. 60
      src/Nacos/Naming/Requests/ListInstancesRequest.cs
  87. 49
      src/Nacos/Naming/Requests/ListServicesRequest.cs
  88. 70
      src/Nacos/Naming/Requests/ModifyInstanceHealthStatusRequest.cs
  89. 97
      src/Nacos/Naming/Requests/ModifyInstanceRequest.cs
  90. 68
      src/Nacos/Naming/Requests/ModifyServiceRequest.cs
  91. 41
      src/Nacos/Naming/Requests/ModifySwitchesRequest.cs
  92. 101
      src/Nacos/Naming/Requests/RegisterInstanceRequest.cs
  93. 72
      src/Nacos/Naming/Requests/RemoveInstanceRequest.cs
  94. 44
      src/Nacos/Naming/Requests/RemoveServiceRequest.cs
  95. 62
      src/Nacos/Naming/Requests/SendHeartbeatRequest.cs
  96. 11
      src/Nacos/Naming/Result/BaseHealthParams.cs
  97. 23
      src/Nacos/Naming/Result/BeatInfo.cs
  98. 22
      src/Nacos/Naming/Result/Cluster.cs
  99. 22
      src/Nacos/Naming/Result/ClusterLeader.cs
  100. 23
      src/Nacos/Naming/Result/ClusterServer.cs

46
.github/workflows/build.yml

@ -0,0 +1,46 @@
name: nacos-sdk-csharp CI
on:
push:
branches:
- master
- release/*
jobs:
windows:
name: windows
runs-on: windows-latest
steps:
- uses: actions/checkout@v1
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: 3.1.200
- name: Build with dotnet
run: dotnet build --configuration Release
linux:
name: linux
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- name: Setup .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: 3.1.200
- name: Build with dotnet
run: dotnet build --configuration Release
- name: Pack with dotnet
run: dotnet pack /home/runner/work/nacos-sdk-csharp/nacos-sdk-csharp/nacos-sdk-csharp.sln -o /home/runner/work -c Release --no-build
- name: list temp
run: ls /home/runner/work
# should config Nuget_key
#- name: Push to nuget
# run: |
# for file in /home/runner/work/*.nupkg
# do
# dotnet nuget push $file -k ${{ secrets.Nuget_Key }} --skip-duplicate -s https://www.nuget.org/api/v2/package
# done

333
.gitignore

@ -0,0 +1,333 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/
# Mac OS
.DS_Store

20
Directory.Build.props

@ -0,0 +1,20 @@
<Project>
<PropertyGroup>
<LangVersion>latest</LangVersion>
<RepositoryType>git</RepositoryType>
</PropertyGroup>
<PropertyGroup>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn),1573,1591,1712</NoWarn>
<CodeAnalysisRuleSet>..\..\_stylecop\codeanalysis.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.164">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>

186
README.md

@ -1,2 +1,184 @@
# nacos-sdk-csharp
This nacos csharp sdk
# nacos-sdk-csharp             [中文](./README.zh-cn.md)
csharp(dotnet core) implementation of [nacos](https://nacos.io/) OpenAPI.
![](https://img.shields.io/nuget/v/nacos-sdk-csharp-unofficial.svg)
![](./media/prj.png)
## CI Build Status
| Platform | Build Server | Master Status |
|--------- |------------- |---------|
| Github Action | Linux/Windows |![nacos-sdk-csharp CI](https://github.com/nacos-group/nacos-sdk-csharp/workflows/nacos-sdk-csharp%20CI/badge.svg)
## Installation
```bash
dotnet add package nacos-sdk-csharp-unofficial
```
## Features
- Basic OpenApi Usages
- Integrate ASP.NET Core Configuration System
- Service Registration and Discovery With ASP.NET Core
- Integrate With Aliyun ACM
- ...
## Basic Usage
### Simple Configuration Usage
1. Configure in `Program.cs`
```cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var c = builder.Build();
// read configuration from config files
builder.AddNacosConfiguration(c.GetSection("NacosConfig"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
```
2. Modify `appsettings.json`
```JSON
{
"NacosConfig": {
"Optional": false,
"DataId": "msconfigapp",
"Group": "",
"Tenant": "f47e0ae1-982a-4a64-aea3-52506492a3d4",
"ServerAddresses": [ "http://localhost:8848/" ],
"UserName": "test2",
"Password": "123456",
"AccessKey": "",
"SecretKey": "",
"EndPoint": "acm.aliyun.com"
}
}
```
3. Use via .NET Core's Way
```cs
[ApiController]
[Route("api/[controller]")]
public class ConfigController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly AppSettings _settings;
private readonly AppSettings _sSettings;
private readonly AppSettings _mSettings;
public ConfigController(
IConfiguration configuration,
IOptions<AppSettings> options,
IOptionsSnapshot<AppSettings> sOptions,
IOptionsMonitor<AppSettings> _mOptions
)
{
_logger = logger;
_configuration = configuration;
_settings = options.Value;
_sSettings = sOptions.Value;
_mSettings = _mOptions.CurrentValue;
}
[HttpGet]
public string Get()
{
// ....
return "ok";
}
}
```
### Service Registration and Discovery
1. Service Registration
Configure in `Program.cs`
```cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddNacosAspNetCore(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
}
}
```
Modify `appsettings.json`
```JSON
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "",
"ListenInterval": 1000,
"ServiceName": "App1"
}
```
2. Service Discovery
```cs
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly INacosServerManager _serverManager;
public ValuesController(INacosServerManager serverManager)
{
_serverManager = serverManager;
}
[HttpGet("test")]
public async Task<IActionResult> Test()
{
// need to know the service name.
// at this time only support random way.
var baseUrl = await _serverManager.GetServerAsync("App2");
if(string.IsNullOrWhiteSpace(baseUrl))
{
return "empty";
}
var url = $"{baseUrl}/api/values";
using (HttpClient client = new HttpClient())
{
var result = await client.GetAsync(url);
return await result.Content.ReadAsStringAsync();
}
}
}
```

185
README.zh-cn.md

@ -0,0 +1,185 @@
# nacos-sdk-csharp             [English](./README.md)
基于C#(dotnet core)实现 [nacos](https://nacos.io/) OpenAPI 的非官方版本
![](https://img.shields.io/nuget/v/nacos-sdk-csharp-unofficial.svg)
![](./media/prj.png)
## CI构建状态
| Platform | Build Server | Master Status |
|--------- |------------- |---------|
| Github Action | Linux/OSX |![nacos-sdk-csharp CI](https://github.com/catcherwong/nacos-sdk-csharp/workflows/nacos-sdk-csharp%20CI/badge.svg)
|
## 安装Nuget包
```bash
dotnet add package nacos-sdk-csharp-unofficial
```
## 功能特性
- 基本的Open Api接口封装
- 集成ASP.NET Core的配置系统
- 简易ASP.NET Core的服务注册和发现
- 和阿里云应用配置管理(Application Configuration Management,简称 ACM)集成使用
- ...
## 简易用法
### 配置
1. 在 `Program.cs` 进行如下配置
```cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var c = builder.Build();
// read configuration from config files
builder.AddNacosConfiguration(c.GetSection("NacosConfig"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
```
2. 修改 `appsettings.json`
```JSON
{
"NacosConfig": {
"Optional": false,
"DataId": "msconfigapp",
"Group": "",
"Tenant": "f47e0ae1-982a-4a64-aea3-52506492a3d4",
"ServerAddresses": [ "http://localhost:8848/" ],
"UserName": "test2",
"Password": "123456",
"AccessKey": "",
"SecretKey": "",
"EndPoint": "acm.aliyun.com"
}
}
```
3. 用原生的.NET Core方式来读取Nacos配置
```cs
[ApiController]
[Route("api/[controller]")]
public class ConfigController : ControllerBase
{
private readonly IConfiguration _configuration;
private readonly AppSettings _settings;
private readonly AppSettings _sSettings;
private readonly AppSettings _mSettings;
public ConfigController(
IConfiguration configuration,
IOptions<AppSettings> options,
IOptionsSnapshot<AppSettings> sOptions,
IOptionsMonitor<AppSettings> _mOptions
)
{
_logger = logger;
_configuration = configuration;
_settings = options.Value;
_sSettings = sOptions.Value;
_mSettings = _mOptions.CurrentValue;
}
[HttpGet]
public string Get()
{
// ....
return "ok";
}
}
```
### 服务注册和发现
1. 服务注册
`Program.cs` 中配置
```cs
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddNacosAspNetCore(Configuration);
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// ...
}
}
```
修改 `appsettings.json`
```JSON
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "",
"ListenInterval": 1000,
"ServiceName": "App1"
}
```
2. 服务发现
```cs
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly INacosServerManager _serverManager;
public ValuesController(INacosServerManager serverManager)
{
_serverManager = serverManager;
}
[HttpGet("test")]
public async Task<IActionResult> Test()
{
// 这里需要知道被调用方的服务名
// 目前获取服务地址是随机的方式,后续会加入更多负载算法.
var baseUrl = await _serverManager.GetServerAsync("App2");
if(string.IsNullOrWhiteSpace(baseUrl))
{
return "empty";
}
var url = $"{baseUrl}/api/values";
using (HttpClient client = new HttpClient())
{
var result = await client.GetAsync(url);
return await result.Content.ReadAsStringAsync();
}
}
}
```

79
_stylecop/codeanalysis.ruleset

@ -0,0 +1,79 @@
<?xml version="1.0" encoding="utf-8"?>
<RuleSet Name="Catcher Wong Analyzer Rules" Description="Analyzer rules for Nacos CSharp SDK." ToolsVersion="15.0">
<!-- https://github.com/dotnet/roslyn/blob/master/docs/compilers/Rule%20Set%20Format.md -->
<IncludeAll Action="Warning" />
<Rules AnalyzerId="Microsoft.Usage" RuleNamespace="Microsoft.Usage">
<!-- Implement standard exception constructors - not all of the exception constructors (e.g., parameterless) are desired in our system. -->
<Rule Id="CA1032" Action="None" />
<!-- Change names to avoid reserved word overlaps (e.g., Delegate, GetType, etc.) - too many of these in the public API, we'd break if we fixed it. -->
<Rule Id="CA1716" Action="None" />
<!-- Implement serialization constructors - false positive when building .NET Core -->
<Rule Id="CA2229" Action="None" />
<!-- Mark ISerializable types with SerializableAttribute - false positive when building .NET Core -->
<Rule Id="CA2237" Action="None" />
</Rules>
<Rules AnalyzerId="StyleCop.Analyzers" RuleNamespace="StyleCop.Analyzers">
<!-- Prefix local calls with this -->
<Rule Id="SA1101" Action="None" />
<!-- Parameters should be on same line or separate lines -->
<Rule Id="SA1117" Action="None" />
<!-- Use built-in type alias -->
<Rule Id="SA1121" Action="None" />
<!-- Use String.Empty instead of "" -->
<Rule Id="SA1122" Action="None" />
<!-- Using statements must be inside a namespace -->
<!-- <Rule Id="SA1200" Action="None" /> -->
<!-- Enforce order of class members by member type -->
<Rule Id="SA1201" Action="None" />
<!-- Enforce order of class members by member visibility -->
<Rule Id="SA1202" Action="None" />
<!-- Enforce order of constantand static members -->
<Rule Id="SA1203" Action="None" />
<!-- Enforce order of static vs. non-static members -->
<Rule Id="SA1204" Action="None" />
<!-- System using directives should be placed before other using directives -->
<Rule Id="SA1208" Action="None" />
<!-- Enforce order of readonly vs. non-readonly members -->
<Rule Id="SA1214" Action="None" />
<!-- Using directives should be ordered alphabetically by namespace -->
<Rule Id="SA1210" Action="None" />
<!-- Fields can't start with underscore -->
<Rule Id="SA1309" Action="None" />
<!-- Fields Name should not contain underscore -->
<Rule Id="SA1310" Action="None" />
<!-- Fields should be private -->
<Rule Id="SA1401" Action="None" />
<!-- Suppressions must have a justification -->
<Rule Id="SA1404" Action="None" />
<!-- Use trailing comma in initializers - lots of false positives for enums in StyleCop 1.1.0-beta004 -->
<Rule Id="SA1413" Action="None" />
<!-- No single-line statements involving braces -->
<Rule Id="SA1501" Action="None" />
<!-- Braces must not be omitted -->
<Rule Id="SA1503" Action="None" />
<!-- Code should not contain multiple blank lines in a row -->
<Rule Id="SA1507" Action="None" />
<!-- Element must be documented -->
<Rule Id="SA1600" Action="None" />
<!-- Parameter documentation mus be in the right order -->
<Rule Id="SA1612" Action="None" />
<!-- Return value must be documented -->
<Rule Id="SA1615" Action="None" />
<!-- Generic type parameters must be documented -->
<Rule Id="SA1618" Action="None" />
<!-- Don't copy/paste documentation -->
<Rule Id="SA1625" Action="None" />
<!-- Exception documentation must not be empty -->
<Rule Id="SA1627" Action="None" />
<!-- File must have header -->
<Rule Id="SA1633" Action="None" />
<!-- Enable XML documentation output-->
<Rule Id="SA1652" Action="None" />
<!-- Do not user regions-->
<Rule Id="SA1124" Action="None" />
<!-- Documentation text should end with a period -->
<Rule Id="SA1629" Action="None" />
<!-- The property's documentation summary text must begin with: 'Gets or sets' -->
<Rule Id="SA1623" Action="None" />
</Rules>
</RuleSet>

5
build/version.props

@ -0,0 +1,5 @@
<Project>
<PropertyGroup>
<NugetVersion>0.1.0</NugetVersion>
</PropertyGroup>
</Project>

BIN
media/prj.png

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

101
nacos-sdk-csharp.sln

@ -0,0 +1,101 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.28803.156
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{C473C3A7-1B44-4E1F-83C0-745AD0566FE9}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{8176B7FC-151E-4EFF-A693-F60A39109595}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nacos", "src\Nacos\Nacos.csproj", "{6D3AEDBE-B3CF-4CF8-94ED-49E347D740CE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nacos.Tests", "tests\Nacos.Tests\Nacos.Tests.csproj", "{F4B027C1-BBCB-450F-BC4D-76F05F2FB3EB}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nacos.AspNetCore", "src\Nacos.AspNetCore\Nacos.AspNetCore.csproj", "{52E524B7-960D-4FB0-AD79-FF3A4395B613}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{25B1A184-1541-4F4E-A151-24A47CC08F34}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "App1", "samples\App1\App1.csproj", "{60EDEA1E-549B-44EA-8954-FA2AB85966A8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "App2", "samples\App2\App2.csproj", "{2D5914EC-97B4-4AAD-BCBA-6F9FF00F2AAE}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "App3", "samples\App3\App3.csproj", "{17A6F76B-FEC2-419A-8C68-416032D3FBA1}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Nacos.Microsoft.Extensions.Configuration", "src\Nacos.Microsoft.Extensions.Configuration\Nacos.Microsoft.Extensions.Configuration.csproj", "{0E5305FF-6ADA-42E7-A5D1-C576E185F932}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MsConfigApp", "samples\MsConfigApp\MsConfigApp.csproj", "{D8A28493-0320-4C40-8EBB-0D0AE5015307}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nacos.Microsoft.Extensions.Configuration.Tests", "tests\Nacos.Microsoft.Extensions.Configuration.Tests\Nacos.Microsoft.Extensions.Configuration.Tests.csproj", "{11BEE2DE-B793-4868-B65C-FF915125A7DD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6D3AEDBE-B3CF-4CF8-94ED-49E347D740CE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6D3AEDBE-B3CF-4CF8-94ED-49E347D740CE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6D3AEDBE-B3CF-4CF8-94ED-49E347D740CE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6D3AEDBE-B3CF-4CF8-94ED-49E347D740CE}.Release|Any CPU.Build.0 = Release|Any CPU
{F4B027C1-BBCB-450F-BC4D-76F05F2FB3EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F4B027C1-BBCB-450F-BC4D-76F05F2FB3EB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F4B027C1-BBCB-450F-BC4D-76F05F2FB3EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F4B027C1-BBCB-450F-BC4D-76F05F2FB3EB}.Release|Any CPU.Build.0 = Release|Any CPU
{52E524B7-960D-4FB0-AD79-FF3A4395B613}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{52E524B7-960D-4FB0-AD79-FF3A4395B613}.Debug|Any CPU.Build.0 = Debug|Any CPU
{52E524B7-960D-4FB0-AD79-FF3A4395B613}.Release|Any CPU.ActiveCfg = Release|Any CPU
{52E524B7-960D-4FB0-AD79-FF3A4395B613}.Release|Any CPU.Build.0 = Release|Any CPU
{60EDEA1E-549B-44EA-8954-FA2AB85966A8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{60EDEA1E-549B-44EA-8954-FA2AB85966A8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{60EDEA1E-549B-44EA-8954-FA2AB85966A8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{60EDEA1E-549B-44EA-8954-FA2AB85966A8}.Release|Any CPU.Build.0 = Release|Any CPU
{2D5914EC-97B4-4AAD-BCBA-6F9FF00F2AAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{2D5914EC-97B4-4AAD-BCBA-6F9FF00F2AAE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2D5914EC-97B4-4AAD-BCBA-6F9FF00F2AAE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2D5914EC-97B4-4AAD-BCBA-6F9FF00F2AAE}.Release|Any CPU.Build.0 = Release|Any CPU
{17A6F76B-FEC2-419A-8C68-416032D3FBA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{17A6F76B-FEC2-419A-8C68-416032D3FBA1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{17A6F76B-FEC2-419A-8C68-416032D3FBA1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{17A6F76B-FEC2-419A-8C68-416032D3FBA1}.Release|Any CPU.Build.0 = Release|Any CPU
{0E5305FF-6ADA-42E7-A5D1-C576E185F932}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{0E5305FF-6ADA-42E7-A5D1-C576E185F932}.Debug|Any CPU.Build.0 = Debug|Any CPU
{0E5305FF-6ADA-42E7-A5D1-C576E185F932}.Release|Any CPU.ActiveCfg = Release|Any CPU
{0E5305FF-6ADA-42E7-A5D1-C576E185F932}.Release|Any CPU.Build.0 = Release|Any CPU
{D8A28493-0320-4C40-8EBB-0D0AE5015307}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D8A28493-0320-4C40-8EBB-0D0AE5015307}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D8A28493-0320-4C40-8EBB-0D0AE5015307}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D8A28493-0320-4C40-8EBB-0D0AE5015307}.Release|Any CPU.Build.0 = Release|Any CPU
{11BEE2DE-B793-4868-B65C-FF915125A7DD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{11BEE2DE-B793-4868-B65C-FF915125A7DD}.Debug|Any CPU.Build.0 = Debug|Any CPU
{11BEE2DE-B793-4868-B65C-FF915125A7DD}.Release|Any CPU.ActiveCfg = Release|Any CPU
{11BEE2DE-B793-4868-B65C-FF915125A7DD}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{6D3AEDBE-B3CF-4CF8-94ED-49E347D740CE} = {C473C3A7-1B44-4E1F-83C0-745AD0566FE9}
{F4B027C1-BBCB-450F-BC4D-76F05F2FB3EB} = {8176B7FC-151E-4EFF-A693-F60A39109595}
{52E524B7-960D-4FB0-AD79-FF3A4395B613} = {C473C3A7-1B44-4E1F-83C0-745AD0566FE9}
{60EDEA1E-549B-44EA-8954-FA2AB85966A8} = {25B1A184-1541-4F4E-A151-24A47CC08F34}
{2D5914EC-97B4-4AAD-BCBA-6F9FF00F2AAE} = {25B1A184-1541-4F4E-A151-24A47CC08F34}
{17A6F76B-FEC2-419A-8C68-416032D3FBA1} = {25B1A184-1541-4F4E-A151-24A47CC08F34}
{0E5305FF-6ADA-42E7-A5D1-C576E185F932} = {C473C3A7-1B44-4E1F-83C0-745AD0566FE9}
{D8A28493-0320-4C40-8EBB-0D0AE5015307} = {25B1A184-1541-4F4E-A151-24A47CC08F34}
{11BEE2DE-B793-4868-B65C-FF915125A7DD} = {8176B7FC-151E-4EFF-A693-F60A39109595}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {A1C5215E-0E70-4C04-B21E-5209BCF32472}
EndGlobalSection
GlobalSection(MonoDevelopProperties) = preSolution
Policies = $0
$0.DotNetNamingPolicy = $1
$1.DirectoryNamespaceAssociation = PrefixedHierarchical
$0.TextStylePolicy = $2
$2.FileWidth = 80
$2.TabsToSpaces = True
$2.scope = text/plain
$0.VersionControlPolicy = $3
description = nacos sdk csharp
EndGlobalSection
EndGlobal

10
samples/App1/App1.csproj

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Nacos.AspNetCore\Nacos.AspNetCore.csproj" />
</ItemGroup>
</Project>

46
samples/App1/Controllers/ValuesController.cs

@ -0,0 +1,46 @@
namespace App1.Controllers
{
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly INacosServerManager _serverManager;
public ValuesController(INacosServerManager serverManager)
{
_serverManager = serverManager;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2", "App1" };
}
// GET api/values/test
[HttpGet("test")]
public ActionResult<string> Test()
{
var baseUrl = _serverManager.GetServerAsync("App2").GetAwaiter().GetResult();
if (string.IsNullOrWhiteSpace(baseUrl))
{
return "empty";
}
var url = $"{baseUrl}/api/values";
using (HttpClient client = new HttpClient())
{
var result = client.GetAsync(url).GetAwaiter().GetResult();
return result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
}
}

18
samples/App1/Program.cs

@ -0,0 +1,18 @@
namespace App1
{
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://127.0.0.1:9876")
.UseStartup<Startup>();
}
}

41
samples/App1/Startup.cs

@ -0,0 +1,41 @@
namespace App1
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddNacosAspNetCore(Configuration);
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
/*app.UseNacosAspNetCore();*/
}
}
}

9
samples/App1/appsettings.Development.json

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

15
samples/App1/appsettings.json

@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "",
"ListenInterval": 1000,
"ServiceName": "App1"
}
}

10
samples/App2/App2.csproj

@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Nacos.AspNetCore\Nacos.AspNetCore.csproj" />
</ItemGroup>
</Project>

46
samples/App2/Controllers/ValuesController.cs

@ -0,0 +1,46 @@
namespace App2.Controllers
{
using System.Collections.Generic;
using System.Net.Http;
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly INacosServerManager _serverManager;
public ValuesController(INacosServerManager serverManager)
{
_serverManager = serverManager;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2", "App2" };
}
// GET api/values/test
[HttpGet("test")]
public ActionResult<string> Test()
{
var baseUrl = _serverManager.GetServerAsync("App1").GetAwaiter().GetResult();
if (string.IsNullOrWhiteSpace(baseUrl))
{
return "empty";
}
var url = $"{baseUrl}/api/values";
using (HttpClient client = new HttpClient())
{
var result = client.GetAsync(url).GetAwaiter().GetResult();
return result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
}
}

18
samples/App2/Program.cs

@ -0,0 +1,18 @@
namespace App2
{
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseUrls("http://127.0.0.1:9877")
.UseStartup<Startup>();
}
}

41
samples/App2/Startup.cs

@ -0,0 +1,41 @@
namespace App2
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddNacosAspNetCore(Configuration);
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
/*app.UseNacosAspNetCore();*/
}
}
}

9
samples/App2/appsettings.Development.json

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

15
samples/App2/appsettings.json

@ -0,0 +1,15 @@
{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "",
"ListenInterval": 1000,
"ServiceName": "App2"
}
}

11
samples/App3/App3.csproj

@ -0,0 +1,11 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Nacos.AspNetCore\Nacos.AspNetCore.csproj" />
</ItemGroup>
</Project>

46
samples/App3/Controllers/ValuesController.cs

@ -0,0 +1,46 @@
namespace App3.Controllers
{
using Microsoft.AspNetCore.Mvc;
using Nacos.AspNetCore;
using System.Collections.Generic;
using System.Net.Http;
[ApiController]
[Route("[controller]")]
public class ValuesController : ControllerBase
{
private readonly INacosServerManager _serverManager;
public ValuesController(INacosServerManager serverManager)
{
_serverManager = serverManager;
}
// GET api/values
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2", "App3" };
}
// GET api/values/test
[HttpGet("test")]
public ActionResult<string> Test()
{
var baseUrl = _serverManager.GetServerAsync("App1").GetAwaiter().GetResult();
if (string.IsNullOrWhiteSpace(baseUrl))
{
return "empty";
}
var url = $"{baseUrl}/api/values";
using (HttpClient client = new HttpClient())
{
var result = client.GetAsync(url).GetAwaiter().GetResult();
return result.Content.ReadAsStringAsync().GetAwaiter().GetResult();
}
}
}
}

20
samples/App3/Program.cs

@ -0,0 +1,20 @@
namespace App3
{
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}

41
samples/App3/Startup.cs

@ -0,0 +1,41 @@
namespace App3
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddNacosAspNetCore(Configuration);
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
/*app.UseNacosAspNetCore();*/
}
}
}

9
samples/App3/appsettings.Development.json

@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}

17
samples/App3/appsettings.json

@ -0,0 +1,17 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"nacos": {
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "",
"ListenInterval": 1000,
"ServiceName": "App3"
}
}

32
samples/MsConfigApp/AppSettings.cs

@ -0,0 +1,32 @@
namespace MsConfigApp
{
using System.Collections.Generic;
public class AppSettings
{
/*
{
"ConnectionStrings": {
"Default": "Server=127.0.0.1;Port=3306;Database=demo;User Id=root;Password=123456;"
},
"version": "测试version",
"AppSettings": {
"Str": "val",
"num": 1,
"arr": [1, 2, 3],
"subobj": {
"a": "b"
}
}
}
*/
public string Str { get; set; }
public int Num { get; set; }
public List<int> Arr { get; set; }
public SubObj SubObj { get; set; }
}
}

62
samples/MsConfigApp/Controllers/ConfigController.cs

@ -0,0 +1,62 @@
namespace MsConfigApp.Controllers
{
using System;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
[ApiController]
[Route("api/[controller]")]
public class ConfigController : ControllerBase
{
private readonly ILogger<ConfigController> _logger;
private readonly IConfiguration _configuration;
private readonly AppSettings _settings;
private readonly AppSettings _sSettings;
private readonly AppSettings _mSettings;
public ConfigController(
ILogger<ConfigController> logger,
IConfiguration configuration,
IOptions<AppSettings> options,
IOptionsSnapshot<AppSettings> sOptions,
IOptionsMonitor<AppSettings> mOptions)
{
_logger = logger;
_configuration = configuration;
_settings = options.Value;
_sSettings = sOptions.Value;
_mSettings = mOptions.CurrentValue;
}
[HttpGet]
public string Get()
{
string id = Guid.NewGuid().ToString("N");
_logger.LogInformation($"============== begin {id} =====================");
var conn = _configuration.GetConnectionString("Default");
_logger.LogInformation($"{id} conn = {conn}");
var version = _configuration["version"];
_logger.LogInformation($"{id} version = {version}");
var str1 = Newtonsoft.Json.JsonConvert.SerializeObject(_settings);
_logger.LogInformation($"{id} IOptions = {str1}");
var str2 = Newtonsoft.Json.JsonConvert.SerializeObject(_sSettings);
_logger.LogInformation($"{id} IOptionsSnapshot = {str2}");
var str3 = Newtonsoft.Json.JsonConvert.SerializeObject(_mSettings);
_logger.LogInformation($"{id} IOptionsMonitor = {str3}");
_logger.LogInformation($"===============================================");
_logger.LogInformation($"===============================================");
_logger.LogInformation($"===============================================");
return "ok";
}
}
}

17
samples/MsConfigApp/MsConfigApp.csproj

@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="3.2.0" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.7.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\Nacos.Microsoft.Extensions.Configuration\Nacos.Microsoft.Extensions.Configuration.csproj" />
</ItemGroup>
</Project>

79
samples/MsConfigApp/Program.cs

@ -0,0 +1,79 @@
namespace MsConfigApp
{
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Events;
public class Program
{
public static void Main(string[] args)
{
var outputTemplate = "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level}] {Message}{NewLine}{Exception}";
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("System", LogEventLevel.Warning)
.MinimumLevel.Debug()
.WriteTo.Console(
outputTemplate: outputTemplate)
/*.WriteTo.File(
path: "logs/ApiTpl.log",
outputTemplate: outputTemplate,
rollingInterval: RollingInterval.Day,
retainedFileCountLimit: 5,
encoding: System.Text.Encoding.UTF8)*/
.CreateLogger();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
try
{
Log.ForContext<Program>().Information("Application starting...");
CreateHostBuilder(args).Build().Run();
}
catch (System.Exception ex)
{
Log.ForContext<Program>().Fatal(ex, "Application start-up failed!!");
}
finally
{
Log.CloseAndFlush();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((context, builder) =>
{
var c = builder.Build();
var dataId = c.GetValue<string>("NacosConfig:DataId");
var group = c.GetValue<string>("NacosConfig:Group");
var tenant = c.GetValue<string>("NacosConfig:Tenant");
var optional = c.GetValue<bool>("NacosConfig:Optional");
var serverAddresses = c.GetSection("NacosConfig:ServerAddresses").Get<List<string>>();
// read configuration from config files
builder.AddNacosConfiguration(c.GetSection("NacosConfig"));
// hard code here
/*builder.AddNacosConfiguration(x =>
{
x.DataId = dataId;
x.Group = group;
x.Tenant = tenant;
x.Optional = optional;
x.ServerAddresses = serverAddresses;
});*/
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
})
.UseSerilog();
}
}

41
samples/MsConfigApp/Startup.cs

@ -0,0 +1,41 @@
namespace MsConfigApp
{
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

9
samples/MsConfigApp/SubObj.cs

@ -0,0 +1,9 @@
namespace MsConfigApp
{
public class SubObj
{
#pragma warning disable SA1300 // Element should begin with upper-case letter
public string a { get; set; }
#pragma warning restore SA1300 // Element should begin with upper-case letter
}
}

16
samples/MsConfigApp/appsettings.json

@ -0,0 +1,16 @@
{
"NacosConfig": {
"Optional": false,
"DataId": "msconfigapp",
"Group": "",
"Tenant": "f47e0ae1-982a-4a64-aea3-52506492a3d4",
//"Tenant": "",
"ServerAddresses": [ "http://localhost:8848/" ],
"UserName": "test2",
"Password": "123456",
//"ServerAddresses": [],
"AccessKey": "",
"SecretKey": "",
"EndPoint": "acm.aliyun.com"
}
}

9
src/Nacos.AspNetCore/INacosServerManager.cs

@ -0,0 +1,9 @@
namespace Nacos.AspNetCore
{
using System.Threading.Tasks;
public interface INacosServerManager
{
Task<string> GetServerAsync(string serviceName);
}
}

19
src/Nacos.AspNetCore/LoadBalance/ILBStrategy.cs

@ -0,0 +1,19 @@
namespace Nacos.AspNetCore
{
using System.Collections.Generic;
public interface ILBStrategy
{
/// <summary>
/// Strategy Name
/// </summary>
LBStrategyName Name { get; }
/// <summary>
/// Get instance
/// </summary>
/// <param name="list">server list</param>
/// <returns>The instance</returns>
string GetInstance(List<NacosServer> list);
}
}

20