出现最多问题就是版本问题
直接上版本
Springboot版本 2.3.12.RELEASE
Nacos服务端:2.0.4
Nacos Spring Project 版本:0.2.12
1、因为Nacos服务端是远程的服务器上的,所以版本不可调整,所以只能根据Nacos服务端版本来选择其它两个版本 2、Nacos Spring Project 只有0.2.10以上支持内置了2.1.0的nacos-client所以版本只能选择0.2.10以上,在此选择0.2.12 3、springboot版本选择,可根据此链接进行选择 https://github.com/alibaba/spring-cloud-alibaba/wiki/%E7%89%88%E6%9C%AC%E8%AF%B4%E6%98%8E 具体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.3.12.RELEASE</version>
<relativePath/>
</parent>
<properties>
<java.version>1.8</java.version>
<nacos.version>0.2.12</nacos.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<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.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${nacos.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
这里配置application.yaml文件(也可配置bootstrap.yaml)
spring:
application:
name: demo
nacos:
config:
server-addr: 192.168.2.1:8848
namespace: 6cb7bd99-a669-42e5-aeac-564e9a057321
group: test
username: nacos
password: nacos
server:
port: 8989
编写DemoApplication主程序入口 这里主要填写dataId值
@SpringBootApplication
@NacosPropertySource(dataId = "demo-dev.yaml",,autoRefreshed = true)
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
编写controller访问属性 这里使用@NacosValue获取属性 必须要有默认值,不然会启动报注解错误
@RestController
@RequestMapping("/test")
public class TestController {
@NacosValue(value = "${redis.port:8080}",autoRefreshed = true)
private String port;
@RequestMapping("/get")
public String get(@RequestParam String serviceName) throws NacosException {
return port;
}
}
最后贴上nacos的配置文件内容(yaml)
redis:
port: 6379
|