GuLi商城-SpringCloud Alibaba-Nacos配置中心-简单示例

GitHub - alibaba/spring-cloud-alibaba: Spring Cloud Alibaba provides a one-stop solution for application development for the distributed solutions of Alibaba middleware.

spring-cloud-alibaba/readme-zh.md at 2022.x · alibaba/spring-cloud-alibaba · GitHub

因为版本问题,上面最新的文档没有使用bootstrap.properties,

下面我们用的是bootstrap.properties配置


1.引入配置中心依赖,放到common中

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

2. 在优惠券微服务中创建/src/main/resources/bootstrap.properties ,这个文件是springboot里规定

的,它的优先级比application.properties高

spring.application.name=gulimall-coupon

spring.cloud.nacos.config.server-addr=127.0.0.1:8848

测试,用传统方式:

 

这样做存在的一个问题,如果频繁的修改application.properties,在需要频繁重新打包部署。下面

我们将采用Nacos的配置中心来解决这个问题。 

3.给配置中心添加一个叫数据集(Data id)gulimall-coupon.properties 默认规则 ,应用

名.properties

coupon.user.name=zhangsan
coupon.user.age=24

DataID:gulimall-coupon

配置格式:properties

文件的命名规则为:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

${spring.application.name}:为微服务名

${spring.profiles.active}:指明是哪种环境下的配置,如dev、test或info

${spring.cloud.nacos.config.file-extension}:配置文件的扩展名,可以为properties、yml等

4.修改CouponController类,添加@RefreshScope注解

@RefreshScope :动态刷新nacos配置

@RestController
@RequestMapping("coupon/coupon")
@RefreshScope
public class CouponController {
   
   

这样会动态的从配置中心读取配置,并且在指明了相同的配置信息时,配置中心中设置的值优先

于本地配置。

配置中心是zhangsan 24,本地是lisi 20

我们测试下配置中心中设置的值是不是优先于本地配置,结果失败了,没有读取配置中心的值。

nacos在springboot 2.4.0之后的版本不再使用Bootstrap container,改为spring.config.import方式

引入 

在common服务中新增依赖:

在SpringBoot 2.4.x的版本之后,对于bootstrap.properties/bootstrap.yaml配置文件(我们合起来成为Bootstrap配置文件)的支持,需要导入如下的依赖
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-bootstrap -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
    <version>3.1.5</version>
</dependency>

再次测试ok,读取到了配置中心的值:

参考:

gulimall-learning/谷粒商城—分布式基础.md at master · OYCodeSite/gulimall-learning · GitHub

谷粒商城-day03-服务配置中心Nacos和网关Gateway_nacos服务分组 网关如何区分_周周写不完的代码的博客-CSDN博客

谷粒商城笔记 + 完整代码 + 课件资料(基础篇)(学习记录)_谷粒商城资料_待别三日的博客-CSDN博客

谷粒商城-微服务-注册中心-配置中心-网关_注册中心 网关_saudadessss的博客-CSDN博客

谷粒商城分布式基础篇1-个人版_断河愁的博客-CSDN博客

SpringCloudAlibaba—Nacos config_spring-cloud-starter-alibaba-nacos-config_JagTom的博客-CSDN博客

nacos 1.4.2 + springboot 2.4.2 实现配置中心+自动刷新_qq_16320351的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/ZHOU_VIP/article/details/129677401