最重要的是依赖的版本,版本不对的话,可能导致无法找到对应的key、系统启动时不加载等问题。以下依赖是支持nacos2.0.3 最低版本,部分升级到较高版本正在测试中
启动类
package com.zrh.jserver;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
public class JServerApplication {
public static void main(String[] args) throws InterruptedException {
ConfigurableApplicationContext applicationContext = SpringApplication.run(JServerApplication.class, args);
while(true){
String userName = applicationContext.getEnvironment().getProperty("dev.port");
String userAge = applicationContext.getEnvironment().getProperty("dev.server");
System.err.println("user name :" + userName + "; age: " + userAge);
Thread.sleep(10000);
}
}
}
jserver pom.xml
4.0.0 com.zrh jserver0.0.1-SNAPSHOT pom jserver jsd server 1.8 UTF-8 UTF-8 2.4.1 start jserver-api jserver-common jserver-dao jserver-service org.springframework.boot spring-boot-dependencies2.3.12.RELEASE pom import org.springframework.cloud spring-cloud-dependenciesHoxton.SR12 pom import com.alibaba.cloud spring-cloud-alibaba-dependencies2.2.7.RELEASE pom import org.projectlombok lombok1.18.22 com.alibaba fastjson1.2.78 org.apache.maven.plugins maven-compiler-plugin3.8.1 1.8 1.8 UTF-8 org.apache.maven.plugins maven-deploy-plugin2.8.2 true
start pom.xml
4.0.0 start com.zrh jserver0.0.1-SNAPSHOT ../pom.xml org.springframework.boot spring-boot-starter-webcom.alibaba.cloud spring-cloud-starter-alibaba-nacos-configorg.projectlombok lombok
bootstrap.properties
spring.cloud.nacos.config.server-addr=10.2.57.237:8848 spring.cloud.nacos.config.namespace=9f5d8328-55b8-48f1-a450-249bb434c20e spring.cloud.nacos.config.extension-configs[0].data-id=jserver-dev.properties spring.cloud.nacos.config.extension-configs[0].group=ZRH_GROUP spring.cloud.nacos.config.extension-configs[0].refresh=true
Config.controller
package com.zrh.jserver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("config")
@RefreshScope // 必须
public class ConfigController {
@Value("${dev.server}")
private String mc;
@RequestMapping(value = "/get")
public String get() {
System.out.println("1222222222222" + mc);
return mc;
}
}
curl http://localhost:8080/config/get



