美文网首页
Springboot 整合 Nacos

Springboot 整合 Nacos

作者: fdsun | 来源:发表于2020-04-27 19:05 被阅读0次

整合步骤

  • 1 pom.xml引入依赖
    注意:版本 0.2.x.RELEASE 对应的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 对应的是 Spring Boot 1.x 版本。
<!-- 这里的的springboot使用的是2.2.6.RELEASE -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.1</version>
</dependency>
  • 2 application.properties配置文件中添加
#nacos地址 ip:port, 例如127.0.0.1:8848
nacos.config.server-addr=ip:port
  • 3 springboot的启动类上添加注解
@NacosPropertySource(dataId = "dataId", autoRefreshed = true)
  • 4 简单使用(两步)
    a.nacos控制台中添加配置(Properties配置格式)
    b.通过@NacosValue(value = "${config}", autoRefreshed = true)注解使用

使用样例
nacos中的配置内容(properties配置格式)

city={"001":{"cityName":"shanghai","cityUrl":"www"},"002":{"cityName":"niuyue","cityUrl":"xxx"},"003":{"cityName":"shouer","cityUrl":"yyy","cityNull":"null"}}

启动类

@SpringBootApplication
@NacosPropertySource(dataId = "dataId", autoRefreshed = true)
public class DemoNacosApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoNacosApplication.class, args);
    }

model实体类

public class CityInfo {
    private String cityName;
    private String cityUrl;
    // get,set,toString
}

controller

@RestController
@RequestMapping("/config")
public class NacosTestController {

    @NacosValue(value = "${city}", autoRefreshed = true)
    private String city;

    @GetMapping("nacos")
    public Object getValues(String cityCode){
        // 从nacos中获取数据 fastJson
        JSONObject jsonObject = JSON.parseObject(city);
        System.out.println("nacos-config:"+city);

        // 根据key获取对象
        CityInfo info = jsonObject.getObject(cityCode, CityInfo.class);
        System.out.println(cityCode+"的info:"+info);

        return info;
    }
}

相关文章

网友评论

      本文标题:Springboot 整合 Nacos

      本文链接:https://www.haomeiwen.com/subject/yjzywhtx.html