Skip to content

Commit

Permalink
add a csharp sdk-examples #48
Browse files Browse the repository at this point in the history
  • Loading branch information
heqingpan committed Dec 18, 2024
1 parent 5c4aa8d commit eb11bc9
Show file tree
Hide file tree
Showing 11 changed files with 269 additions and 0 deletions.
3 changes: 3 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
bin/
obj/
.idea/
8 changes: 8 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/Biz/AppFooConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace nacos_csharp_01.Biz;

public class AppFooConfig
{
public string? Name { get; set; }
public int? Value { get; set; }
public string? Remark { get; set; }
}
52 changes: 52 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/Biz/AppFooListener.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using System.Text.Json;
using Nacos.V2;

namespace nacos_csharp_01.Biz;

public class AppFooListener: IListener
{
private readonly ILogger<AppFooListener> _logger;

private AppFooConfig? _config;

private readonly INacosConfigService _nacosConfigService;

public AppFooConfig? GetAppFooConfig()
{
return _config;
}

public AppFooListener(ILogger<AppFooListener> logger, INacosConfigService nacosConfigService)
{
this._logger = logger;
this._nacosConfigService = nacosConfigService;
}

public async Task AsyncInit()
{
try
{
_logger.LogInformation("AppFooListener is starting.");
await _nacosConfigService.AddListener("foo_config.json", "DEFAULT_GROUP", this);
string configInfo = await _nacosConfigService.GetConfig("foo_config.json","DEFAULT_GROUP",5000);
ReceiveConfigInfo(configInfo);
}
catch (Exception ex)
{
_logger.LogError(ex, "AppFooListener is starting failed.");
}
}

public void ReceiveConfigInfo(string configInfo)
{
_logger.LogInformation($"Received config info: {configInfo}");
try
{
this._config = JsonSerializer.Deserialize<AppFooConfig>(configInfo);
}
catch (Exception ex)
{
_logger.LogError($"Failed to parse config info: {configInfo}", ex);
}
}
}
25 changes: 25 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/Biz/MyHostedService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace nacos_csharp_01.Biz;

public class MyHostedService: IHostedService
{
private readonly ILogger<MyHostedService> _logger;
private readonly AppFooListener _appFooListener;

public MyHostedService(ILogger<MyHostedService> logger, AppFooListener appFooListener)
{
this._appFooListener = appFooListener;
this._logger = logger;
}

public async Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("MyHostedService is starting.");
await _appFooListener.AsyncInit();
}

public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("MyHostedService is stopping.");
return Task.CompletedTask;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using Microsoft.AspNetCore.Mvc;
using nacos_csharp_01.Biz;
using Nacos.V2;

namespace nacos_csharp_01.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ConfigController
{
private readonly ILogger<ConfigController> _logger;
private readonly AppFooListener _appFooListener;
private readonly INacosConfigService _nacosConfigService;

public ConfigController(AppFooListener appFooListener, INacosConfigService nacosConfigService,
ILogger<ConfigController> logger)
{
this._logger = logger;
this._appFooListener = appFooListener;
this._nacosConfigService = nacosConfigService;
}

[HttpGet("get")]
public async Task<String> Get(String key)
{
_logger.LogInformation("Get config:"+key);
var res = await _nacosConfigService.GetConfig(key,"DEFAULT_GROUP",3000).ConfigureAwait(false);
return res ?? "[empty config]";
}

[HttpGet("set")]
public async Task<String> Set(String key)
{
_logger.LogInformation("Publish config:"+key);
var res = await _nacosConfigService.PublishConfig(key,"DEFAULT_GROUP",new System.Random().Next(1,999999).ToString()).ConfigureAwait(false);
return "Publish ok,"+res;
}

[HttpGet("get_config_name")]
public String GetConfigName()
{
var res = _appFooListener.GetAppFooConfig()?.Name;
return res ?? "[empty foo config]";
}
}
20 changes: 20 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
using nacos_csharp_01.Biz;
using Nacos.AspNetCore.V2;
using Nacos.V2.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddNacosV2Naming(builder.Configuration);
builder.Services.AddNacosV2Config(builder.Configuration);
builder.Services.AddNacosAspNet(builder.Configuration);

builder.Services.AddControllers();
builder.Services.AddSingleton<AppFooListener>();
builder.Services.AddHostedService<MyHostedService>();

var app = builder.Build();

app.MapGet("/", () => "Hello World!");
app.MapControllers();

app.Run();
38 changes: 38 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"$schema": "http://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:65406",
"sslPort": 44347
}
},
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5142",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7166;http://localhost:5142",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
16 changes: 16 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# nacos-csharp 说明

配置中心使用样例

## 使用方式

1. 启动r-nacos
2. 运行应用, 在本项目目录运行: `dotnet run --urls 'http://*:5215'`
3. 访问应用接口:
+ 设置配置 `curl -i 'http://127.0.0.1:5215/api/config/set?key=abc'`
+ 获取配置 `curl -i 'http://127.0.0.1:5215/api/config/set?key=abc'`
+ 获取指定应用配置 `curl -i 'http://127.0.0.1:5215/api/config/get_config_name`
4. 验证动态修改配置能力,在r-nacos控制台中修改第3步对应的配置内容再查询配置内容信息会更新;



Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
39 changes: 39 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"nacos": {
"EndPoint": "",
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "net-test",
"ListenInterval": 1000,
"ServiceName": "App2",
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"Ip": "",
"PreferredNetworks": "",
"Port": 0,
"Weight": 100,
"RegisterEnabled": true,
"InstanceEnabled": true,
"Ephemeral": true,
"Secure": false,
"AccessKey": "",
"SecretKey": "",
"UserName": "",
"Password": "",
"ConfigUseRpc": true,
"NamingUseRpc": true,
"NamingLoadCacheAtStart": "",
"Metadata": {
"preserved.register.source": "Test",
"aa": "bb",
"cc": "dd"
}
},
"AllowedHosts": "*"
}
15 changes: 15 additions & 0 deletions sdk-examples/csharp/nacos-csharp-01/nacos-csharp-01.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>nacos_csharp_01</RootNamespace>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="nacos-sdk-csharp" Version="1.3.10" />
<PackageReference Include="nacos-sdk-csharp.AspNetCore" Version="1.3.10" />
</ItemGroup>

</Project>

0 comments on commit eb11bc9

Please sign in to comment.