美文网首页
nacos配置使用

nacos配置使用

作者: 某某程序员_ | 来源:发表于2019-04-28 14:37 被阅读0次

    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 的配置,多个之间用逗号隔开, 按照配置出现的先后顺序,即后面的优先级要高于前面。
    spring.cloud.nacos.config.shared-data-ids=nacos-config-example.properties
    #配置支持动态刷新的Data Id,多个 Data Id 之间用逗号隔开, 默认不支持
    spring.cloud.nacos.config.refreshable-dataids=nacos-config-example.properties
    

    application.properties

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

    实现

    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
    结果:
    userName is zm, age is 2019

    源码地址

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

    相关文章

      网友评论

          本文标题:nacos配置使用

          本文链接:https://www.haomeiwen.com/subject/gavdnqtx.html