nacos配置使用

maven依賴

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

配置

bootstrap.properties

spring.application.name=nacos-config-example
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

#支持多個共享 Data Id 的配置,多個之間用逗號隔開, 按照配置出現(xiàn)的先后順序,即后面的優(yōu)先級要高于前面。
spring.cloud.nacos.config.shared-data-ids=nacos-config-example.properties
#配置支持動態(tài)刷新的Data Id,多個 Data Id 之間用逗號隔開, 默認(rèn)不支持
spring.cloud.nacos.config.refreshable-dataids=nacos-config-example.properties

application.properties

server.port=8081
management.endpoints.web.exposure.include=*

實(shí)現(xiàn)

package com.zm.demo.dubbo.nacosserver;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zoum
 * @create 2019/4/26 14:11
 */
@RestController
@RefreshScope
public class UserController {

    @Value("${user.name}")
    String userName;


    @Value("${user.age}")
    int age;

    @GetMapping("/user")
    public String simple() {
            return "userName is " + userName + ", age is " + age ;
    }
}

啟動類

package com.zm.demo.dubbo.nacosserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

/**
 * @author zoum
 * @create 2019/4/26 11:52
 */
@SpringBootApplication
public class NacosApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosApplication.class, args);
        String userName = applicationContext.getEnvironment().getProperty("user.name");
        String userAge = applicationContext.getEnvironment().getProperty("user.age");
        System.err.println("user name :"+userName+"; age: "+userAge);
    }
}

測試

請求:
http://127.0.0.1:8081/user](http://127.0.0.1:8081/user
結(jié)果:
userName is zm, age is 2019

源碼地址

https://gitee.com/love2014/demo/tree/master/demo-dubbo/nacos-server

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容