Nacos配置管理服务

统一配置管理

功能:对配置文件相同的微服务进行配置文件的统一管理。

统一配置管理是解决场景:普通情况下,多个相同功能的微服务实例,更改配置的话得一个一个更改后重启的情况。

核心配置放在配置管理服务中,启动时微服务读取配置管理服务中的核心配置与自身的配置相结合后启动。

配置管理服务中配置更改后会自动通知所需的微服务,微服务读取后会自动完成热更新

在配置管理->配置列表中添加:

代码配置流程

项目启动->bootstrap.yml->读取nacos配置文件->读取本地application.yml->创建spring容器->加载bean。

1、引入Maven依赖

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

2、创建bootstrap.yml

服务名+开发环境+文件后缀名,组成data id,也就是:${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}

spring:
  application:
    name: userservice #eureka的服务名称
  profiles:
    active: dev  #开发环境
  cloud:
    nacos:
      server-addr: localhost:8848  # nocos服务器地址
      config:
        file-extension: yaml  #文件后缀名

使用的时候:

@Value("${pattern.dateformat}")
private String dateFormat;

配置热更新

更新后大概五秒生效

方法一:使用@RefreshScope

在使用@Value的类上使用@RefreshScope注解能够实现热更新。

@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Value("${pattern.dateformat}")
    private String dateFormat;

    @GetMapping("date")
    public String now() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(dateFormat));
    }
}

 方法二:使用@ConfigurationProperties(推荐)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>
@Data
@Component
@ConfigurationProperties(prefix = "pattern")
public class PatternProperties {
    private String dateformat;
}
@Slf4j
@RestController
@RequestMapping("/user")
@RefreshScope
public class UserController {

    @Autowired
    private PatternProperties properties;
    
    @GetMapping("date")
    public String now() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(properties.getDateformat()));
    }
}

多环境配置共享

有些值在开发、测试、生产的时候值是不变的,就适合用多环境配置共享。

多种配置优先级:服务名-profile.yaml > 服务名称.yaml > 本地配置

猜你喜欢

转载自blog.csdn.net/LYXlyxll/article/details/132456177
今日推荐