springboot集成nacos
- 1.版本
- 2. POM依賴
- 3. nacos服務
- 3.1 下載nacos壓縮包
- 3.2 啟動nacos
- 4. yaml配置
- 5.Demo
- 5.1 配置中心簡單格式獲取方式
- 普通方式還可以再啟動類上添加注解完成
- 5.2 獲取json格式的demo
- 5.2 自動注冊根據yaml配置
1.版本
nacos版本:2.3.2
springboot版本:2.1.3.RELEASE
2. POM依賴
<dependency><groupId>com.alibaba.boot</groupId><artifactId>nacos-discovery-spring-boot-starter</artifactId><version>0.2.3</version></dependency><dependency><groupId>com.alibaba.boot</groupId><artifactId>nacos-config-spring-boot-starter</artifactId><version>0.2.3</version></dependency>
3. nacos服務
3.1 下載nacos壓縮包
https://github.com/alibaba/nacos/releases
3.2 啟動nacos
Linux/Unix/Mac
啟動命令(standalone代表著單機模式運行,非集群模式):sh startup.sh -m standalone如果您使用的是ubuntu系統,或者運行腳本報錯提示[[符號找不到,可嘗試如下運行:bash startup.sh -m standaloneWindows
啟動命令(standalone代表著單機模式運行,非集群模式):startup.cmd -m standalone
4. yaml配置
nacos:discovery:server-addr: 127.0.0.1:8848enabled: trueautoRegister: true# 指定本項目的注冊地址和端口號 這里配置的數元數據register:metadata:gRPC-port: 19090
5.Demo
5.1 配置中心簡單格式獲取方式
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)private boolean useLocalCache;@GetMapping("getNacos")public Result getNacos() throws NacosException {return ResultGenerator.getSuccessResult(useLocalCache);}
結果:
普通方式還可以再啟動類上添加注解完成
@NacosPropertySources(value = {@NacosPropertySource(dataId = "example", groupId = "TEST_GROUP", autoRefreshed = true),@NacosPropertySource(dataId = "example", autoRefreshed = true),@NacosPropertySource(dataId = "testList", autoRefreshed = true)})
5.2 獲取json格式的demo
@Configuration
public class NacosConfig {@Value("${nacos.config.server-addr}")private String serverAdd;@Value("${nacos.config.namespace:}")private String namespace;@Beanpublic ConfigService configService() throws NacosException {final Properties properties = new Properties();//設置Nacos節點對應的IP地址properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAdd);//設置命名空間properties.setProperty(PropertyKeyConst.NAMESPACE, namespace);//如果開啟了Nacos權限校驗,設置用戶名
// properties.setProperty(PropertyKeyConst.USERNAME,"nacos");
// properties.setProperty(PropertyKeyConst.PASSWORD,"nacos");//設置獲取配置信息的輪詢超時時間properties.setProperty(PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT, "3000");//設置獲取配置信息失敗后的重試次數properties.setProperty(PropertyKeyConst.CONFIG_RETRY_TIME, "5");//設置是否開啟客戶端主動拉取最新的配置信息properties.setProperty(PropertyKeyConst.MAX_RETRY, "5");//構造一個ConfigService實例ConfigService configService = NacosFactory.createConfigService(properties);return configService;}}@RestController
@RequestMapping("test")
@Slf4j
public class TestController {@Autowiredprivate ConfigService configService;@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)private boolean useLocalCache;@GetMapping("getNacos")public Result getNacos() throws NacosException {String config = configService.getConfig("testjson", "DEFAULT_GROUP", 3000);getConfig();return ResultGenerator.getSuccessResult(useLocalCache);}}
結果:
5.2 自動注冊根據yaml配置
enabled: true
autoRegister: true
當然可以在啟動類上添加注解
@EnableNacosDiscovery