SpringCloud + SpringBoot 整合Nacos作配置中心 【二】

新建配置
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
创建服务

1.引入依赖:

     <dependencies>
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
    </dependencies>

2、创建配置文件名为bootstrap.yml,注意是bootstrap.xxx,而不是application或者其他。原因如下

Nacos同springcloud-config一样,在项目初始化时,要保证先从配置中心进行配置拉取,拉取配置之后,才能保证项目的正常启动。springboot中配置文件的加载是存在优先级顺序的,bootstrap优先级高于application

spring:
  application:
  #服务名称
    name: nacos-config
  cloud:
    nacos:
      discovery:
      #连接注册中心 指定注册中心的地址,如果你不需要注册该服务,也可以去掉该项,
        server-addr: 192.168.230.136:8848
          #连接配置 指定配置中心的地址
      config:
        server-addr: 192.168.230.136:8848
        file-extension: yml

启动类加注解:

package com.fh;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient
public class NacosConfigApplication {

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

}

创建控制层进行测试

package com.fh.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("config")
@RefreshScope //使当前类下的配置支持动态更新
public class NacosConfigController {

    @Value("${nacos.config}") //读取key为nacosconfig的配置的值
    private String config;

    @RequestMapping("/getValue")
    public String getValue() {
        return config;
    }


}

在浏览器访问 http://localhost:10002/config/getValue

效果1:

在这里插入图片描述
效果2:
在这里插入图片描述
值来源:
在这里插入图片描述
此时说明已经成功读取到配置,下面我将Nacos-Server上的配置修改为bacos,看看能否动态更新,如下图:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jq1223

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值