用Java和C# SDK获取nacos配置

分布式配置nacos搭建踩坑指南(下) 这篇文章里,我在nacos后台创建了一个配置,下面我们来看如何用Java和c#来获取这个配置.

一.Java

  1.启动nacos,和前面文章介绍的一样。

  2.下载阿里巴巴脚手架,引入:spring-cloud-starter,spring-cloud-starter-alibaba-nacos-config,完整pom如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.11</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>nacos-discovery-providerbysdk</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>nacos-discovery-providerbysdk</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud-alibaba.version>2021.0.4.0</spring-cloud-alibaba.version>
        <spring-cloud.version>2021.0.4</spring-cloud.version>
    </properties>

    <dependencies>
   
      
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    </dependency>

        
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

3.Java代码

package com.alibaba.cloud;

import java.util.Properties;
import java.util.concurrent.Executor;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;


public class main {

  public static void main(String[] args) throws NacosException {
    // TODO Auto-generated method stub
    

    String serverAddr = "localhost:8848";
    String dataId = "nacos-config-sample.properties";
    dataId="config2";
    String group = "DEFAULT_GROUP";
    
    Properties properties=new Properties();
    properties.put(PropertyKeyConst.SERVER_ADDR  , serverAddr);
    ConfigService configService=NacosFactory.createConfigService(properties);
    
    //test1 get config
    String contentString=configService.getConfig(dataId, group, 5000);
    System.out.println(contentString);
    
    //test2 refresh config
//    configService.addListener(dataId, group, new Listener() {
//      @Override
//      public void receiveConfigInfo(String configInfo) {
//        System.out.println("recieve:" + configInfo);
//      }
//
//      @Override
//      public Executor getExecutor() {
//        return null;
//      }
//    });
//    while (true) {
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }
    
    
    //test3 push config
    boolean isPublishOk = configService.publishConfig(dataId, group, "content");
    System.out.println(isPublishOk);
  }

}

其中test1 get config是读取配置,test2 refresh config是刷新配置,test3 push config是刷新配置。需要注意的是,serverAddr是nacos服务器的地址和端口号,dataId是配置的dataId,group是配置所在的组

 二.C#

 1.新建一个netcore控制台程序,引入nuget包:nacos-sdk-csharp

 2.C#代码:

using System;
using Microsoft.Extensions.DependencyInjection;
using Nacos.V2;
using Nacos.V2.DependencyInjection;
using System.Collections.Generic;
using System.Threading.Tasks;

using System;
using Microsoft.Extensions.DependencyInjection;
using Nacos.V2;
using Nacos.V2.DependencyInjection;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace NacosDiscoveryProviderNetCoreTest1
{
    class Program
    {
        static async Task Main(string[] args)
        {
            string serverAddr = "http://localhost:8848";
            string dataId = "config2";
            string group = "DEFAULT_GROUP";

            IServiceCollection services = new ServiceCollection();


            //test1 read config 
            services.AddNacosV2Config(
                 x =>
                 {
                     x.ServerAddresses = new List<string>() { serverAddr };

                 }
                );
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var configSvc = serviceProvider.GetService<INacosConfigService>();
            var content = await configSvc.GetConfig(dataId, group, 3000);
            Console.WriteLine(content);

        }
    }
}

 

posted @ 2023-03-04 09:40  王三丰  阅读(478)  评论(0编辑  收藏  举报