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>
相关推荐
Solis5 分钟前
Raft:分布式系统的定海神针
后端·架构
小狮子&6 分钟前
ubuntu2604无法共享文件夹问题解决
linux·运维·服务器
沪漂阿龙7 分钟前
《LangChain 系列》Human-in-the-loop:什么时候必须让人工介入?
人工智能·架构·langchain
思茂信息10 分钟前
CST软件基于液态金属开关的方向图可重构天线
服务器·算法·重构·cst·仿真软件·电磁仿真
zhping101116 分钟前
Ubuntu 登录密码忘记
运维·服务器·ubuntu
Benszen29 分钟前
Secret详解
linux·运维·服务器
makise-32 分钟前
破译大数据底层密码:从 HDFS 存储基石到现代分布式计算引擎的架构演进
大数据·hdfs·架构
烈焰晴天40 分钟前
Codex 桌面端如何链接Figma MCP 服务器拿到 Figma设计稿精准尺寸等结构化数据 来精准还原UI
服务器·ui·figma
zzqssliu40 分钟前
基于策略模式与责任链的代购商品多源采集架构实战
架构·策略模式