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>
相关推荐
ElevenS_it1887 分钟前
连锁门店IT运维监控实战:200+门店网络设备+POS统一纳管+按区域分组告警路由完整配置(Zabbix Proxy架构)
运维·网络·架构·zabbix
dualven_in_csdn11 分钟前
mqtt消息及日志查看
linux·运维·服务器
ting945200031 分钟前
深度解析 Google Stitch 3.0:文本驱动跨端 UI 生成技术原理、架构与工程实现
人工智能·ui·架构
Yupureki1 小时前
《MySQL数据库基础》9.索引原理
linux·运维·服务器·网络·数据库·mysql
X54先生(人文科技)1 小时前
关于“778之问”与“X54之答”的文明范式校验报告
人工智能·架构·开源·开源协议
Yupureki2 小时前
《MySQL数据库基础》8.复合查询
linux·运维·服务器·网络·数据库·mysql
方芯半导体2 小时前
ST系列MCU EtherCAT协议栈框架结构详解
服务器·网络·数据库·网络协议·机器人·自动化·工业以太网
jiayong232 小时前
RAG系列(三):实践案例与高级优化
ai·架构·rag·智能体
上海云盾安全满满2 小时前
海外服务器使用高防CDN的优势
运维·服务器
Mortalbreeze2 小时前
进程间通信 ---- System V 共享内存
linux·运维·服务器