声明:本站文章均为作者个人原创,图片均为实际截图。如有需要请收藏网站,禁止转载,谢谢配合!!!

两种方式进行Nacos配置热更新

一些自定义配置配置热更新,可以不用重启nacos服务吗,提升效率和用户体验

@Value注入,结合@RefreshScope实现热更新

import org.springframework.cloud.context.config.annotation.RefreshScope;

@RefreshScope
public class UserController {

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

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

}

@ConfigurationProperties注入实现热更新

1、新建一个属性类

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

@Data
@ConfigurationProperties(prefix = "pattern")
@Component //将类注册为bean,被其他类使用
public class PatternProperties {
    private String dateformat;
}

2、使用

public class UserController {

    @Autowired
    private PatternProperties properties;

    @GetMapping("/now")
    public String now(){
        String s = properties.getDateformat();
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern(s));
    }
}