21

SpringCloud Nacos 配置中心

 4 years ago
source link: http://www.eknown.cn/index.php/springcloud/config-nacos.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

上一篇介绍了 Spring Cloud 中配置中心的使用,地址: https://mp.weixin.qq.com/s/QcIaGAYUvPBIqJM8oMbVvQ

这一节介绍 Nacos 作为配置中心使用,不需要 Github

这里首先需要注意,Nacos 在Spring、Spring Boot、Spring Cloud 这三种环境下的依赖、配置和使用方法都是不同的。这里仅以 Spring Cloud + Nacos 为例,阐述 Spring Cloud 中使用 Nacos 作为服务注册中心和配置中心。更具体的资料可以参考官方文档: https://nacos.io/zh-cn/docs/quick-start.html

一、Nacos Server 创建配置

启动 Nacos Server 端,浏览器访问。

在 Nacos 中创建三个配置文件: consumer-demo.yamlconsumer-demo-dev.yamlconsumer-demo-prod.yaml ,内容略有区别。

i2EfAbz.png!web

consumer-demo.yml

JbmyUna.png!web

二、Nacos-Consumer

创建一个 consumer-demo 项目,依赖如下:

<properties>
    <java.version>1.8</java.version>
    <spring-cloud.version>Hoxton.SR3</spring-cloud.version>
    <nacos.version>0.9.0.RELEASE</nacos.version>
</properties>

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>${nacos.version}</version>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

在启动类加上 @EnableDiscoveryClient 注解(这表示是启用服务注册,也可以不启用而仅从 Nacos 读取配置信息)。

删除 application.yml

配置信息应写在 bootstrap.propertiesbootstrap.yml 文件中:

spring:
  application:
    name: consumer-demo
  cloud:
    nacos:
      config:
        file-extension: yaml
        server-addr: 127.0.0.1:8848
        prefix: ${spring.application.name} # 默认值就是 spring.application.name
      discovery:
        server-addr: 127.0.0.1:8848
  profiles:
    active: dev

查找的配置文件,即 nacos 中的 dataId,应该是: ${prefix}-${spring.profile.active}.${file-extension}

如果 ${active} 不存在,那么会查找: ${prefix}.${file-extension}

启动项目,控制台出现类似如下信息:

2020-04-15 17:00:17.946  INFO 16392 --- [           main] o.s.c.a.n.c.NacosPropertySourceBuilder   : Loading nacos data, dataId: 'consumer-demo.yaml', group: 'DEFAULT_GROUP'
2020-04-15 17:00:17.953  INFO 16392 --- [           main] o.s.c.a.n.c.NacosPropertySourceBuilder   : Loading nacos data, dataId: 'consumer-demo-dev.yaml', group: 'DEFAULT_GROUP'
2020-04-15 17:00:17.955  INFO 16392 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-consumer-demo-dev.yaml'}, BootstrapPropertySource {name='bootstrapProperties-consumer-demo.yaml'}]
2020-04-15 17:00:17.960  INFO 16392 --- [           main] c.e.c.ConsumerDemoApplication            : The following profiles are active: dev

我们可以看到从 Nacos 加载了 consumer-demo.yaml 和 consumer-demo-dev.yaml

编写一个测试接口:

@RefreshScope // 注意要加上 @RefreshScope 注解,否则即使 RefreshEventListener 检测到配置信息被更新了,下面的 msg 还是会保持之前的值
@RestController
@RequestMapping(value = "test")
public class TestAction {

    @NacosValue("${msg}")
    private String msg; // 用 @NacosValue 获取不到值 (null)

    @Value("${msg}")
    private String vMsg; // 用 @Value 获取到了值

    @GetMapping(value = "")
    public String hello() {
        return msg + ":" + vMsg;
    }
}

打开浏览器,输入 test 接口地址:

faYFnmi.png!web

在 nacos 上修改一下 msg 的值,观察控制台,出现:

2020-04-15 17:11:43.355  INFO 16392 --- [-127.0.0.1_8848] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [msg]

表明检测到 msg 配置信息改变。刷新 test 接口,发现 msg 的值随之改变了。

三、持久化

关闭 nacos server,重新启动,发现上面创建的配置信息没有丢失,这说明 nacos 把配置信息持久化存储了。

Nacos 默认使用嵌入式数据库,也支持修改数据源为 MySQL

参考:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK