Springboot 整合 Nacos

2020-04-27  本文已影响0人  fdsun

整合步骤

<!-- 这里的的springboot使用的是2.2.6.RELEASE -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.1</version>
</dependency>
#nacos地址 ip:port, 例如127.0.0.1:8848
nacos.config.server-addr=ip:port
@NacosPropertySource(dataId = "dataId", 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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读