Nacos-配置热更新【自动刷新】

发布时间 2023-11-13 09:00:28作者: 角刀牛Java

Nacos中的配置文件变更后,微服务无需重启就可以感知,通过下面两种配置实现:

方式一:在@Value注入的变量所在类上添加注解@RefreshScope

 

方式二:使用@ConfigurationProperties注解读取配置文件内容

复制代码
package cn.itcast.user.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "pattern") //只要前缀名和变量名两者拼接与配置配置文件一致,就能完成属性的自动注入
public class PatternProperties {
    private String dateformat;
}
复制代码
复制代码
package cn.itcast.user.web;

import cn.itcast.user.config.PatternProperties;
import cn.itcast.user.pojo.User;
import cn.itcast.user.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

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

    @Autowired
    private UserService userService;

//    @Value("${pattern.dateformat}")
//    private String dateformate;
    @Autowired
    private PatternProperties patternProperties;

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

    /**
     * 路径: /user/110
     *
     * @param id 用户id
     * @return 用户
     */
    @GetMapping("/{id}")
    public User queryById(@PathVariable("id") Long id) {
        System.out.println(id);
        return userService.queryById(id);
    }
}
复制代码

Nacos配置更改后,微服务可以实现热更新,方式:

  (1) 通过@Value注解注入,结合@RefreshScope来刷新

  (2)通过@ConfigurationProperties注入,自动刷新

注意事项: 不是所有的配置都适合放到配置中心,维护起来比较麻烦 建议将一些关键参数,需要运行时调整的参数放到nacos配置中心,一般都是自定义配置