go和asp.netCore读取nacos配置

上文docker安装nacos我们已经安装了nacos,现在我们来看看如何读取配置文件。我们的nacos的示例采用和 go读取consul配置文件 一致:

 

go

我这里采用 https://github.com/nacos-group/nacos-sdk-go 客户端, 直接上上代码:

package main

import (
    "fmt"
    "log"
    "strings"
    "time"

    "github.com/nacos-group/nacos-sdk-go/clients"
    "github.com/nacos-group/nacos-sdk-go/common/constant"
    "github.com/nacos-group/nacos-sdk-go/vo"
    "github.com/spf13/viper"
)

var (
    defaultConfig *viper.Viper
    nacosIp       string
    nacosPort     uint64
    nacosDataId   string
    nacosGroup    string
)

func initConfig() *viper.Viper {
    nacosIp = "192.168.100.21"
    nacosPort = 8848
    nacosDataId = "dev001"
    nacosGroup = "go"

    defaultConfig = viper.New()
    defaultConfig.SetConfigType("yaml")
    //配置模型
    serverConfigs := []constant.ServerConfig{
        {IpAddr: nacosIp, Port: nacosPort},
    }

    //客户端
    nacosClient, err := clients.NewConfigClient(
        vo.NacosClientParam{
            ClientConfig:  &constant.ClientConfig{TimeoutMs: 5000},
            ServerConfigs: serverConfigs,
        },
    )
    if err != nil {
        log.Fatal("nacos初始化错误:", err)
    }

    content, err := nacosClient.GetConfig(vo.ConfigParam{DataId: nacosDataId, Group: nacosGroup})
    if err != nil {
        log.Fatalln("nacos读取配置错误:" + content)
    }

    err = defaultConfig.ReadConfig(strings.NewReader(content))
    if err != nil {
        log.Fatalln("Viper解析配置失败:", err)
    }

        err = nacosClient.ListenConfig(vo.ConfigParam{
            DataId: nacosDataId,
            Group:  nacosGroup,
            OnChange: func(namespace, group, dataId, data string) {
                fmt.Println("config changed group:" + group + ", dataId:" + dataId + ", content:" + data)
                err = defaultConfig.ReadConfig(strings.NewReader(data))
                if err != nil {
                    log.Fatalln("Viper解析配置失败:", err)
                }
            },
        })

    return defaultConfig
}

func GetConfig() *viper.Viper {
    if defaultConfig == nil {
        defaultConfig = initConfig()
    }
    return defaultConfig
}

func main() {
    for {
        host := GetConfig().GetString("store.bicycle.color")
        fmt.Println("consul===", host)
        time.Sleep(time.Second * 10)
    }
}

运行效果:

 asp.netcore

我们把配置文件改为json格式,并创建配置对象

 

 

    public class MongodbHostOptions
    {
        public string Connection { get; set; }
        public string DataBase { get; set; }

        public string Table { get; set; }
    }

我们采用https://github.com/nacos-group/nacos-sdk-csharp 这个包添加引用:

dotnet add package nacos-sdk-csharp-unofficial
dotnet add package nacos-sdk-csharp-unofficial.AspNetCore
dotnet add package nacos-sdk-csharp-unofficial.Extensions.Configuration
dotnet add package nacos-sdk-csharp-unofficial.YamlParser
dotnet add package nacos-sdk-csharp-unofficial.IniParser

修改Program.cs

  public static IHostBuilder CreateHostBuilder(string[] args) =>
           Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((context, builder) =>
        {
            var c = builder.Build();
            builder.AddNacosConfiguration(c.GetSection("NacosConfig"));
            // builder.AddNacosConfiguration(c.GetSection("NacosConfig"), Nacos.IniParser.IniConfigurationStringParser.Instance);
  
        })
        .ConfigureWebHostDefaults(webBuilder =>
        {
            webBuilder.UseStartup<Startup>();
        });

修改Startup.cs

       public void ConfigureServices(IServiceCollection services)
        {
            services.AddNacos(Configuration);
            services.Configure<MongodbHostOptions>(Configuration.GetSection("MongodbHost"));
            services.AddControllers();
        }

修改使用的地方WeatherForecastController.cs

 private readonly ILogger<WeatherForecastController> _logger;
        MongodbHostOptions _options;
        public WeatherForecastController(IOptionsSnapshot<MongodbHostOptions> options, ILogger<WeatherForecastController> logger)
        {
            _logger = logger;
            _options = options.Value;
        }

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)] + _options.Connection
            })
            .ToArray();
        }

运行结果:

 

更新后也会刷新

 

posted on 2021-02-05 18:44  dz45693  阅读(2391)  评论(0编辑  收藏  举报

导航