Skip to content

nacos集成

参考https://nacos.io/zh-cn/docs/quick-start-spring-boot.html

https://github.com/alibaba/spring-cloud-alibaba/wiki/版本说明

一、springboot集成(配置中心)

  1. 依赖:

                 <!--        nacos配置中心-->
                <dependency>
                    <groupId>com.alibaba.boot</groupId>
                    <artifactId>nacos-config-spring-boot-starter</artifactId>
                    <version>${nacos.version}</version>
                </dependency>
  2. application的配置:

    nacos.config.server-addr=127.0.0.1:8848
  3. 使用 @NacosPropertySource 加载 dataIdexample 的配置源,并开启自动更新(自行决定):

    @SpringBootApplication
    @NacosPropertySource(dataId = "example", autoRefreshed = true)
    public class NacosConfigApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NacosConfigApplication.class, args);
        }
    }
  4. 通过 Nacos 的 @NacosValue 注解设置属性值。

    @Controller
    @RequestMapping("config")
    public class ConfigController {
    
        @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
        private boolean useLocalCache;
    
        @RequestMapping(value = "/get", method = GET)
        @ResponseBody
        public boolean get() {
            return useLocalCache;
        }
    }
  5. 启动 NacosConfigApplication,调用 curl http://localhost:8080/config/get,返回内容是 false

  6. 通过调用 Nacos Open API 向 Nacos server 发布配置:dataId 为example,内容为useLocalCache=true

    curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP&content=useLocalCache=true"
  7. 再次访问 http://localhost:8080/config/get,此时返回内容为true,说明程序中的useLocalCache值已经被动态更新了。

二、springboot集成(注册中心)

  1. 依赖:

               <!--        nacos注册中心-->
                <dependency>
                    <groupId>com.alibaba.boot</groupId>
                    <artifactId>nacos-discovery-spring-boot-starter</artifactId>
                    <version>${nacos.version}</version>
                </dependency>
  2. application的配置:

    nacos.discovery.server-addr=127.0.0.1:8848
  3. 使用 @NacosInjected 注入 Nacos 的 NamingService 实例:

    @Controller
    @RequestMapping("discovery")
    public class DiscoveryController {
    
        @NacosInjected
        private NamingService namingService;
    
        @RequestMapping(value = "/get", method = GET)
        @ResponseBody
        public List<Instance> get(@RequestParam String serviceName) throws NacosException {
            return namingService.getAllInstances(serviceName);
        }
    }
    
    @SpringBootApplication
    public class NacosDiscoveryApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NacosDiscoveryApplication.class, args);
        }
    }
  4. 启动 NacosDiscoveryApplication,调用 curl http://localhost:8080/discovery/get?serviceName=example,此时返回为空 JSON 数组[]

  5. 通过调用 Nacos Open API 向 Nacos server 注册一个名称为 example 服务

    curl -X PUT 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=example&ip=127.0.0.1&port=8080'
  6. 再次访问 curl http://localhost:8080/discovery/get?serviceName=example,此时返回内容为:

[
  {
    "instanceId": "127.0.0.1-8080-DEFAULT-example",
    "ip": "127.0.0.1",
    "port": 8080,
    "weight": 1.0,
    "healthy": true,
    "cluster": {
      "serviceName": null,
      "name": "",
      "healthChecker": {
        "type": "TCP"
      },
      "defaultPort": 80,
      "defaultCheckPort": 80,
      "useIPPort4Check": true,
      "metadata": {}
    },
    "service": null,
    "metadata": {}
  }
]

三、springcloud集成

依赖(注意:版本 2.1.x.RELEASE 对应的是 Spring Boot 2.1.x 版本。版本 2.0.x.RELEASE 对应的是 Spring Boot 2.0.x 版本,版本 1.5.x.RELEASE 对应的是 Spring Boot 1.5.x 版本),参考https://github.com/alibaba/spring-cloud-alibaba/wiki/版本说明:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>${latest.version}</version>
</dependency>

在 Nacos Spring Cloud 中,dataId 的完整格式如下:

plain
${prefix}-${spring.profiles.active}.${file-extension}
  • prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。

  • spring.profiles.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档注意:当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}

  • file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 propertiesyaml 类型。

  1. 通过 Spring Cloud 原生注解 @RefreshScope 实现配置自动更新:
@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

    @Value("${useLocalCache:false}")
    private boolean useLocalCache;

    @RequestMapping("/get")
    public boolean get() {
        return useLocalCache;
    }
}