Ignore the empty nacos configuration and get it based on dataId&nacos配置中心 踩坑

被坑惨了

1.pom.xml

<?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.1.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com</groupId>
    <artifactId>test-3</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>test-3</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>0.9.0.RELEASE</version>
        </dependency>
    </dependencies>

</project>

2.yml

server:
  port: 6666
spring:
  application:
    name: config
  cloud:
    nacos:
      config:
        server-addr: localhost:8848//nacos客户端访问位置
        file-extension: yml
  profiles:
    active: dev

 

这段一定要看懂    

 

${prefix}-${spring.profile.active}.${file-extension}

  • prefix默认为spring.application.name的值,也可以通过配置项spring.cloud.nacos.config.prefix`来配置

  • spring.profile.active即为当前环境对应的profile。注意:当spring.profile.active为空时,对应的连接符-也将不存在,dataId的拼接格式变成${prefix}.${file-extension}

  • file-extension为配置内容的数据格式,可以通过配置项为spring.cloud.nacos.config.file-extension来配置。目前只支持propertiesyaml类型。

3.应用controller

@RestController
@RefreshScope//实时更新
public class Configg {
    @Value("${config.code}")
    private String code;
@GetMapping("/cong")
    public String cong(){
    return code;
}
}

4.启动

5.用浏览器    localhost:6666/cong

总结

一定要先建项目,再根据项目建nacos配置

 

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>