spring cloud 集成nacos config discovery最新

废话不多说直接上代码

  1. 首先创建一个spring boot maven项目

  2. pom文件增加依赖

    
    
        4.0.0
        
            org.springframework.boot
            spring-boot-starter-parent
            2.3.9.RELEASE
             
        
        com.example
        nacosDemo
        0.0.1-SNAPSHOT
        nacosDemo
        Demo project for Spring Boot
        
            1.8
        
        
            
                org.springframework.boot
                spring-boot-starter-web
            
    
            
                com.alibaba.cloud
                spring-cloud-starter-alibaba-nacos-config
                2.2.3.RELEASE
            
    
            
                com.alibaba.cloud
                spring-cloud-starter-alibaba-nacos-discovery
                2.2.3.RELEASE
            
    
            
                org.springframework.boot
                spring-boot-starter-test
                test
            
        
    
        
            
                
                    org.springframework.boot
                    spring-boot-maven-plugin
                
            
        
    
    
    
    
    image.gif
  3. 在application.properties文件中添加配置

    spring.application.name=agent
    spring.cloud.nacos.config.server-addr=127.0.0.1:8848
    spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
    //定义配置文件后缀为.properties
    spring.cloud.nacos.config.file-extension=properties
    //此处为自定义命名空间,下面会有说明
    spring.cloud.nacos.config.namespace=29de6443-9f76-4c4b-9ff2-f754961365d4
    //此处为自定义分组,下面有说明
    spring.cloud.nacos.config.group=OLD_GROUP
    
    image.gif
  4. 在启动类里面加上

    @EnableDiscoveryClient
    
  5. 在配置类上面添加实现当前类属性动态更新

    @RefreshScope
    
    package com.example.nacosdemo;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.context.config.annotation.RefreshScope;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    @RefreshScope
    @RestController
    @EnableDiscoveryClient
    public class NacosDemoApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NacosDemoApplication.class, args);
        }
    
        @Value("${redis.host}")
        private String config;
    
        @RequestMapping("/getValue")
        public String getValue() {
            return config;
        }
    }
    
    
    image.gif
  6. 官网下载nacos-server,启动nacos

  7. 创建命名空间
    image
    image.gif
  8. 创建dataid,配填写配置
    image
    image.gif
  9. 完成以上操作即可顺利启动

你可能感兴趣的:(spring cloud 集成nacos config discovery最新)