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>
相关推荐
lhrimperial6 分钟前
企业智能知识库助手落地实践:从RAG到Multi-Agent
java·spring cloud·微服务·系统架构·知识图谱
糖~醋排骨1 小时前
DHCP服务的搭建
linux·服务器·网络
huohaiyu1 小时前
网络中的一些基本概念
运维·服务器·网络
dust_and_stars1 小时前
ubuntu24使用apt安装VS-code-server code-server
linux·服务器·windows
小小工匠1 小时前
LLM - 从定制化 Agent 到 Universal Agent + Skills Library:下一代智能体架构实践
架构·定制化agent·universal agent·skill library
ling-452 小时前
Linux-day09 11
linux·运维·服务器
zbguolei2 小时前
Debian提示:“用户名” 不是 sudoers 文件
linux·服务器·debian
neoooo2 小时前
🍃Spring Boot 多模块项目中 Parent / BOM / Starter 的正确分工
java·后端·架构
菜鸟的迷茫2 小时前
为了防雪崩加了限流,结果入口先挂了
java·后端·架构