27 微服务配置拉取

1)引入nacos-config依赖

首先,在user-service服务中,引入nacos-config的客户端依赖:

复制代码
<!--nacos配置管理依赖-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

2)添加bootstrap.yaml

然后,在user-service中添加一个bootstrap.yaml文件,内容如下:

复制代码
spring:
  application:
    name: userservice # 服务名称
  profiles:
    active: dev #开发环境,这里是dev 
  cloud:
    nacos:
      server-addr: localhost:8848 # Nacos地址
      config:
        file-extension: yaml # 文件后缀名

3)读取nacos配置

在user-service中的UserController中添加业务逻辑,读取pattern.dateformat配置:

复制代码
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${pattern.dateformat}")
    private String dateformat;
    
    @GetMapping("now")
    public String now(){
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateformat));
    }
    // ...略
}

注意不要听弹幕的用@NacosValue,就是用@Value,不是lombok包的,是org.springframework.beans.factory.annotation.Value包

bootstrap的依赖也不需要导入

复制代码
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
            <version>3.1.0</version>
        </dependency>
相关推荐
AAA修煤气灶刘哥18 分钟前
为什么你的Codex 重连到 5/5 才开始工作?理解重试、协议回退与代理链路
人工智能·架构·openai
一条Go2 小时前
Kubernetes 多集群接入:kubeconfig 只进不出
后端·架构·github
怕浪猫12 小时前
全球 3D 网络地球的实时通信节点,来看看这四种交互地球,满足你对物理互联网的所有好奇
面试·架构·github
ZhengEnCi15 小时前
项目越写越乱?先别改架构:用一次目录重排 + 一份可复算的体检脚本把乱治住
python·架构·ai编程
速捷工控 PLC触摸屏还原程序17 小时前
欧姆龙NB上传密码忘了,换屏前怎么保留原程序?
运维·服务器·欧姆龙
爱勇宝18 小时前
SSL 证书别再手动续了:acme.sh + Let's Encrypt + 云厂商 DNS 全自动实战
运维·服务器
wy_hhxx18 小时前
《Agent设计模式 图解可复用智能体架构》上篇内容整理
设计模式·架构·ai agent
用户76155938363819 小时前
如何绕过 Rust 孤儿规则
架构
HelloWorld00119 小时前
面对不可逆外部支付回调:基于 TCC 与最大努力通知保证分布式资产终态一致性
架构
你三大爷19 小时前
Seata全局锁泄漏:从上游PR-backport到生产零事故发布实战
架构